Java solved paper-2021| Java Question Paper solved-BCA

1. Answer the following questions:

(i) Which of the following options leads to the portability and security of Java?

(a) Byte code is executed by JVM

(b) The applet makes the Java code secure and portable

(c) Use of exception handling

(d) Dynamic binding between objects.

(ii) Which of the following is not a Java feature?

(a) Dynamic

(b) Architecture Neutral

(c) Use of pointers

(d) Object oriented

(iii) Evaluate the following Java expression if x=3, y=5 and z=10

++z +y -y +z +x++

  1. 24
  2. 23
  3. 20
  4. 25

(iv) What is the output of the below code

class increment {

          public static void main(String args[])

          {

                    int g=3;

                    System.out.print(++g *8);

          }

}

  1. 32
  2. 33
  3. 24
  4. 25

(v) Which statement is true about Java?

(a) Java is a sequence dependent programming language

(b) Java is a code dependent programming language

(c) Java is a platform dependent programming language

(d) Java is a platform independent programming language

(vi) Which of the following is not an OOPs concept in Java?

(a) Polymorphism

(b) Inheritance

(c) Compilation

(d) Encapsulation

(vii) What is not the use of “this” keyword in Java?

(a) Reference to the instance variable when a local variable has the same name

(b) Passing itself to the method of the same class

(c) Passing itself to another method

(d) Calling another constructor in constructor chaining

(viii) Which of the following is a type of polymorphism in Java programming?

(a) Multiple polymorphism

(b) Compile time polymorphism

(c) Multilevel polymorphism

(d) Execution time polymorphism

(ix) What will be output of the following Java code?

class output

{

public static void main(String args[])

          {

                    int x=y=z=20;

          }

}

  1. Compile time error
  2. Run time error
  3. 20
  4. Compile and runs fine

(x) Abstract class cannot have a constructor

(a) True

(b) False

2. Answer the following questions.

a. What are the different features of Java programming? Explain.

Ans: Java is a versatile, object-oriented programming language that is widely used for developing various types of applications. It comes with a rich set of features that contribute to its popularity and flexibility.

Here are some key features of Java programming:

Simple and Easy to Learn: Java was designed to be easy to use and understand, especially for developers familiar with C++. It eliminates the complexity of C++. Java does not use pointers, preprocessor header files, goto statement and many others. It also eliminates operator overloading and multiple inheritance.

Object-Oriented: Java is a fully object-oriented programming language, emphasizing the use of classes and objects. Almost everything in Java is an object. All concepts of OOP are maintained in Java. It follows the principles of encapsulation, inheritance, abstraction and polymorphism.

Platform Independence (Write Once, Run Anywhere – WORA): Java applications can run on any device that has a Java Virtual Machine (JVM). This platform independence is achieved by compiling Java code into an intermediate form called bytecode, which can be executed on any device with a compatible JVM.

Compiled and interpreted: Java is both a compiled and an interpreted language. Usually, a computer language is either compiled or interpreted. Java combines both these approaches thus making Java a two-stage system. First Java compiler translates source code into bytecode. Bytecodes are not machine instructions and therefore, in the second stage, java interpreter generates machine code that can be directly executed by the machine that is running the Java program. We can thus say that Java is both a compiled and an interpreted language.  

Portable: The portability aspect of Java refers to the ability of Java programs to be executed on different platforms without modification. The most significant contribution of Java over other languages is its portability. Java programs can be easily moved from one computer system to another, anywhere and anytime. Changes and upgrades in operating systems, processors and system resources will not force any changes in Java programs.

Distributed: Java is designed as a distributed language for creating applications on networks. It has the ability to share both data and programs. Java applications can open and access remote objects on Internet as easily as they can do in a local system. This enables multiple programmers at multiple remote locations to collaborate and work together on a single project. Java supports distributed computing through its built-in features like Remote Method Invocation (RMI) and Java Remote Method Protocol (JRMP). These allow objects to invoke methods on remote machines, making it easier to develop distributed applications.

Multithreaded and Interactive: Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded programs. This means that we need not wait for the application to finish one task before beginning another. Java’s multithreading feature allows the execution of multiple threads simultaneously. This is essential for developing applications that require concurrent processing and improved performance. The Java runtime comes with tools that support multiprocess synchronization and construct smoothly running interactive systems.

Dynamic and Extensible: Java is dynamic and extensible, supporting dynamic loading of classes. This feature enables the extension of applications by loading classes dynamically at runtime. Java is capable of dynamically linking in new class libraries, methods and objects.

Automatic Memory Management (Garbage Collection): Java’s automatic garbage collection feature helps in managing memory efficiently, reducing the chances of memory leaks and memory-related errors. Java has an automatic garbage collector that manages memory allocation and deallocation. This helps in preventing memory leaks and makes memory management more efficient.

Robust and Secure: Java isrobust and secure programming language due to several built-in features and design principles. It provides many safeguards to ensure reliable code. Java enforces strong type checking at compile-time, reducing the likelihood of type-related errors during runtime. It has a robust exception-handling mechanism that helps developers manage runtime errors effectively. This prevents unexpected crashes and allows for graceful error recovery.

Java includes a Security Manager that allows developers to define and enforce security policies. This provides fine-grained control over the actions that code can perform. The Java Virtual Machine (JVM) verifies bytecode before execution, ensuring that it adheres to Java’s safety rules. This helps prevent the execution of potentially harmful or malformed code.

Rich Standard Library: Java comes with a vast standard library that provides a wide range of pre-built functionality, making it easier for developers to perform common tasks without having to write code from scratch.

High Performance: Java has many features that makes it a high-performance language, including its compiler and runtime system. Java offers good performance through its Just-In-Time (JIT) compilation, which translates bytecode into native machine code at runtime. Java architecture is also designed to reduce overheads during runtime. Further, the incorporation of multithreading enhances the overall execution speed of Java programs.

b. What is a variable? What are the different types of variables used in Java? Explain with a suitable program.

Ans: A variable is a named storage location that holds a value, which can be modified during the execution of a program. Variables are used to store and manipulate data in a program. In Java, variables must be declared with a specific data type before they can be used.

A variable is an identifier that denotes a storage location used to store a data value. Unlike constants that remain unchanged during the execution of a program, a variable may take different values at different times during the execution of the program.

in Java, variables can be categorized into three main types based on their scope and where they are declared:

Instance Variables: Instance variables are declared inside a class but outside of any method, constructor, or block. Instance variables are created when the objects are instantiated and therefore, they are associated with the objects. They take different values for each object.

Instance variables are accessed using the object reference.

public class MyClass {

    // Instance variables

    int instanceVar1;

    String instanceVar2;

}

Class Variables (Static Variables): Class variables, also known as static variables, are shared among all instances of a class. They are declared using the static keyword. Class variables are global to a class and belong to the entire set of objects that class creates. Class variables belong to the class rather than any specific instance and are initialized only once, typically when the class is loaded. They are accessed using the class name.

public class MyClass {

    // Class variables

    static int classVar1;

    static String classVar2;

}

Local Variables: Local variables are declared and used inside a method, constructor, or block. They are temporary and exist only within the scope where they are declared. Local variables must be initialized before use, and they don’t have default values. They are created when the block is entered and destroyed when the block is exited.

public class MyClass {

    // Instance variable

    int instanceVar;

    // Method with local variable

    public void myMethod() {

        // Local variable

        int localVar = 25;

    }

}

Programming Example:

public class VariableType {
    int x=20; // Instance variable
    static int y=10; //Class Variable
    public static void main(String[] args)
    {
        int a=50; // Local Variable
        VariableType var=new VariableType();
        System.out.println(“Value of x =” + var.x);
        System.out.println(“Value of y =” + VariableType.y);
        System.out.println(“Value of a =” + a);
    }
}

Output:

Value of x =20

Value of y =10

Value of a =50

c. What are the rules for access control and inheritance in Java programming?

Ans: In Java programming, access control and inheritance are two important concepts that govern the visibility and usage of classes, methods, and fields in a program.

Access control in Java is managed through access modifiers, which determines the visibility and accessibility of classes, fields, methods, and other members in Java. There are four access modifiers in Java: Public, Protected, Default and Private. They provide different levels of protection as described below:

Public (public):

  • Accessible from any class.
  • No restrictions on access.

Protected (protected):

  • Accessible within the same package and subclasses (even if they are in a different package).
  • Not accessible outside the package if not in a subclass.

Default (no modifier):

  • Accessible only within the same package.
  • Not accessible outside the package.

Private (private):

  • Accessible only within the same class.
  • Not accessible outside the class.

Inheritance:

Inheritance is a mechanism in Java that allows a class (subclass/child) to inherit properties and behaviors from another class (superclass/parent). The extends keyword is used to create a subclass, and the super keyword is used to refer to the superclass.

Rules for Inheritance:

Single Inheritance:

Java supports single inheritance, i.e., a class can only extend one superclass.

class Subclass extends Superclass {

    //…

}

Multilevel Inheritance:

A class can be derived from another class, which is derived from yet another class.

class A { /*… */ }

class B extends A { /*… */ }

class C extends B { /*… */ }

Access Modifiers and Inheritance:

  • Subclass can inherit members (fields and methods) with the public and protected access modifiers.
  • private members are not inherited.
  • Default access members are inherited only if the subclass is in the same package as the superclass.

Constructor in Inheritance:

When a subclass is created, the constructor of its superclass is called implicitly.

class Superclass {

    Superclass() {

        //…

    }

}

class Subclass extends Superclass {

    Subclass() {

        // Implicit call to Superclass constructor

    }

}

Overriding:

Subclasses can provide a specific implementation for a method already defined in the superclass. This is known as method overriding.

class Superclass {

    void display() {

        System.out.println(“Superclass”);

    }

}

class Subclass extends Superclass {

    @Override

    void display() {

        System.out.println(“Subclass”);

    }

}

3. Answer the following questions.

a. What is constructor? How it is different from a method or function? What is the use of a constructor?

Ans: A constructor in Java is a special type of method that is used to initialize objects. It is called when an object of a class is created, and it has the same name as the class. Constructors do not have a return type, not even void. They are primarily used for initializing the instance variables of an object. Constructors are essential for ensuring that objects are properly initialized when they are created, and they play a crucial role in the overall lifecycle of an object in Java. In general, programmers use constructors to provide initial values to the variables represented in the class.

Differences Between Constructor and Method/Function:

ConstructorMethod/Function
Constructor has the same name as the class.Method or function has a distinct name. For the method, we can use any name.
Constructor does not have a return type (not even void).Method or function can have a return type.
Constructor is automatically invoked when an object is created using the new keyword.A Method is invoked through method calls. Method or function is called explicitly by its name.  
Constructors use the new keyword for object creation.Methods or functions are called without the new keyword.
Constructors are used for initializing the state of an object.Methods or functions are used for performing specific actions or computations.
Constructor cannot be inherited by subclasses.Method/Function can be inherited by subclasses.

Use of Constructors:

Initialization: The primary use of a constructor is to initialize the attributes or properties of an object to specific values.

Object Creation: Constructors are automatically called when an object is created, ensuring proper initialization.

Overloading: Like methods, constructors can be overloaded, which means that a class can have multiple constructors with different parameter lists. This allows objects to be created with different initial states.

Default Constructor: If a class does not have any constructor defined, Java provides a default constructor (with no parameter), which initializes the attributes to default values.

b. What is a copy constructor? Explain copy constructor with a suitable Java Program.

Ans: A copy constructor is a special type of constructor that creates a new object as a copy of an existing object. The primary purpose of a copy constructor is to initialize an object by copying the values of another object of the same class. Copy constructors are particularly useful when we want to create a new object that is an exact copy of an existing object, avoiding issues related to shallow copying. We can create copy constructor by defining a constructor that takes an object of the same class as a parameter and initializes the new object by copying the values from the provided object.

Programming example of copy constructor:

public class Rectangle {
    int length;
    int breadth;

 Rectangle(int l, int b)
{
  length=l;
  breadth=b;
}
Rectangle(Rectangle obj)
{
    length=obj.length;
    breadth=obj.breadth;
}
int area()
{
    return length*breadth;
}
}
class CopyConstructor{
    public static void main(String[] args)
    {
        Rectangle OriginalRectangle=new Rectangle(5,6);
        Rectangle CopiedRectangle=new Rectangle(OriginalRectangle);
        System.out.println(“Area of original rectangle:” +OriginalRectangle.area());
        System.out.println(“Area of copied rectangle:” +CopiedRectangle.area());
    }
}

Output:

Area of original rectangle:30

Area of copied rectangle:30

In this example:

  • The Rectangle class has a parameterized constructor and a copy constructor.
  • The area() method is used to display the area of a rectangle.
  • An originalRectangle object is created using the parameterized constructor.
  • A copiedRectangle object is created using the copy constructor, taking the originalRectangle as a parameter.
  • The area of both the original and copied rectangle are displayed.

c. What is Polymorphism? Explain static polymorphism using suitable Java Program.

Ans: Polymorphism in object-oriented programming (OOP) refers to the ability of a single entity, such as a method or class, to take on multiple forms. It allows objects of different types to be treated as objects of a common type. This enables a single interface to represent different underlying implementations. There are two types of polymorphism in Java: static polymorphism (also known as compile-time polymorphism) and dynamic polymorphism (runtime polymorphism).

Static polymorphism is achieved through method overloading. Method overloading occurs when a class has multiple methods with the same name but different parameter lists (different number or types of parameters). The correct method to invoke is determined at compile time based on the number and types of arguments provided.

Here’s an example of static polymorphism in Java:

public class MethodOverload {

    // Method to add two integers
    public int add(int num1, int num2) {
        return num1 + num2;
    }
    // Method to add three integers
    public int add(int num1, int num2, int num3) {
        return num1 + num2 + num3;
    }
    // Method to add two doubles
    public double add(double num1, double num2) {
        return num1 + num2;
    }

    public static void main(String[] args) {
        MethodOverload obj = new MethodOverload();

        // Using the add method with two integers
        System.out.println(“Sum of two integers: ” + obj.add(5, 10));

        // Using the add method with three integers
        System.out.println(“Sum of three integers: ” + obj.add(5, 10, 15));

        // Using the add method with two doubles
        System.out.println(“Sum of two doubles: ” + obj.add(2.5, 3.5));
    }
}

In this example, the MethodOverload class has three add methods with different parameter lists. The first method adds two integers, the second method adds three integers, and the third method adds two doubles. The correct method is determined at compile time based on the number and types of arguments provided.

In the main method, an instance of the methodOverload class is created, and the add methods are called with different sets of arguments. The appropriate add method is chosen at compile time based on the method signature.

4. Answer the following questions:

a. What is default constructor in java? How it is different form parameterized constructor?

Ans: In Java, a default constructor is a constructor that is automatically created by the compiler if a class doesn’t explicitly define any constructor. It is a constructor with no parameters or one that has all parameters provided with default values. If a class does not contain any constructor, Java automatically provides a default constructor.

Here’s an example of a class with a default constructor:

public class MyClass {

    // Default constructor

    public MyClass() {

        // Initialization or setup code (if needed)

    }

// Other methods and members can be defined here

}

If we don’t provide any constructor in the class, the Java compiler will insert a default constructor during compilation.

On the other hand, a parameterized constructor is a constructor that accepts parameters, allowing us to initialize the object’s state with specific values at the time of creation. Unlike the default constructor, a parameterized constructor explicitly takes one or more parameters.

While the default constructor is automatically provided if not explicitly defined, the parameterized constructor allows us to provide specific values during object creation, offering more flexibility in initializing object state.

Here’s an example of a class with a parameterized constructor:

public class Person {

    String name;

    int age;

    // Parameterized constructor

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

    // Other methods and members can be defined here

}

In this example, the Person class has a parameterized constructor that takes a name and an age as parameters. When an object of the Person class is created using this constructor, we can initialize the object with specific values.

Differences between Default Constructor and Parameterized Constructor:

Default ConstructorParameterized Constructor
The default constructor has no parameters.The parameterized constructor has one or more parameters.
The default constructor typically initializes the object with default values or performs minimal setup.The parameterized constructor allows us to initialize the object with specific values provided as arguments.
The default constructor is automatically provided by the compiler if no constructors are defined in the class.  The parameterized constructor is explicitly defined in the class and can be customized based on the specific requirements of object initialization.  

b. Explain the use of BufferedReader class with suitable Java program.

Ans: BufferedReader class in Java is part of the java.io package and is used for reading the text from a character-based input stream. It makes the performance fast, especially when reading large amounts of data, by using a buffer to store data in memory before reading or writing. This reduces the number of interactions with the underlying input or output stream. Using BufferedReader is especially helpful when reading user input because it provides a more efficient way to read lines compared to using Scanner or other methods. Additionally, it can be used to read from files or other input streams with similar efficiency benefits.

Programming example of using BufferedReader to read input from the console:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class BufferedReaderExample {

    public static void main(String[] args) throws IOException {

        // Create BufferedReader object to read from System.in (console)

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            // Prompt the user for input

            System.out.print(“Enter your name: “);

// Read a line of text from the console

            String name = reader.readLine();

// Display the entered name

            System.out.println(“Hello, ” + name + “!”);

}

}

Explanation:

Creating BufferedReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

Creates a BufferedReader object to read from the console (System.in). InputStreamReader is used to convert bytes into characters.

Reading Input:

String name = reader.readLine();

Uses the readLine() method of BufferedReader to read a line of text from the console.

Displaying Output:

System.out.println(“Hello, ” + name + “!”);

Displays a greeting message using the input obtained from the user.

c. Explain the use of “this” keyword and how it is different from super keyword. Explain its use using suitable Java Program.

Ans: In Java, this keyword is used to refer to the current object. It is often used within instance methods or constructors to differentiate between instance variables and parameters with the same name. The this keyword is used to resolve the ambiguity and explicitly refer to the instance variable.

On the other hand, the super keyword is used to refer to the immediate parent class object. It is used to invoke the methods, variables, or constructors of the parent class. This is particularly useful in cases of method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass.

Here’s a simple Java program to illustrate the use of this and super:


class Animal {
    String name;
    Animal(String name) {
        this.name = name;
    }
    void eat() {
        System.out.println(“Animal is eating.”);
    }
}
class Dog extends Animal {
    String breed;
    Dog(String name, String breed) {
        super(name); // Invoking the constructor of the superclass
        this.breed = breed;
    }
    void display() {
        System.out.println(“Name: ” + this.name); // Using ‘this’ to refer to the instance variable
        System.out.println(“Breed: ” + this.breed);
        super.eat(); // Using ‘super’ to invoke the eat method of the superclass
        this.eat(); // Invoking the eat method of the current class
    }
    // Method overriding
    @Override
    void eat() {
        System.out.println(“Dog is eating.”);
    }
}

public class keywords {
    public static void main(String[] args) {
        Dog myDog = new Dog(“Buddy”, “Labrador”);
        myDog.display();
    }
}

In this example:

  • The Animal class has an instance variable name and a method eat.
  • The Dog class extends Animal and has an additional instance variable breed. The constructor of Dog uses super(name) to invoke the constructor of the Animal class and initializes the name variable. The display method uses this to refer to the instance variables of the current class and super to invoke the eat method of the superclass.
  • The main method creates an instance of the Dog class and calls its display method.

5. Answer the following questions:

a. What is method overriding? How it is different from method overloading? Explain method overriding using suitable Java program.

Ans: Method overriding is a feature in object-oriented programming where a subclass provides a specific implementation for a method that is already defined in its superclass. In other words, a subclass can replace or override the implementation of a method that it inherits from its superclass. To perform method overriding, the method in the subclass must have the same signature (name, return type, and parameter types) as the method in the superclass.

Difference between Method Overriding and Method Overloading:

Method Overriding:

  • Involves providing a specific implementation for a method in the subclass that is already defined in the superclass.
  • The method signature (name, return type, and parameter types) must be the same in both the superclass and the subclass.
  • Achieves runtime polymorphism.
  • Requires an “is-a” relationship between the superclass and subclass.

Method Overloading:

  • Involves defining multiple methods in the same class with the same name but different parameter lists (different number or types of parameters).
  • The methods must have the same name but different parameter lists.
  • Achieves compile-time polymorphism.
  • Does not depend on inheritance.

Method Overriding Example:

class Animal {

   public void displayInfo() {

      System.out.println(“I am an animal.”);

   }

}

class Dog extends Animal {

   @Override

   public void displayInfo() {

      System.out.println(“I am a dog.”);

   }

}

class Override{

   public static void main(String[] args) {

      Dog d1 = new Dog();

      d1.displayInfo();

   }

}

Output:

I am a dog.

In the above program, the displayInfo() method is present in both the Animal superclass and the Dog subclass.

When we call displayInfo() using the d1 object (object of the subclass), the method inside the subclass Dog is called. The displayInfo() method of the subclass overrides the same method of the superclass.

b. What is an array? How can we declare an array and allocate memory in Java? Explain with a Java program to take an array of integer type and print the sum of the inserted values in the declared array.

Ans: An array in Java is a data structure that allows us to store multiple values of the same data type under a single name. Each element in the array is identified by its index, and the index starts from 0. Arrays provide a convenient way to work with collections of data.

Declaration and Memory Allocation:

To declare an array in Java, you specify the type of the elements followed by the array name and square brackets. Memory for the array is allocated using the new keyword, specifying the size of the array.

We can declare and allocate memory in array using the following syntax:

// Declaration

dataType[] arrayName;

// Memory Allocation

arrayName = new dataType[arraySize];

Example: Sum of Elements in an Integer Array:

 import java.util.Scanner;
public class ArraySum {
    public static void main(String[] args) {
        // Declare and allocate memory for an integer array of size 5
        int[] numbers = new int[5];
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);
        // Input values into the array
        System.out.println(“Enter 5 integers:”);
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(“Enter number ” + (i + 1) + “: “);
            numbers[i] = scanner.nextInt();
        }
        // Calculate and print the sum of elements in the array
        int sum = 0;
        for(int i=0;i<numbers.length;i++) {
            sum += numbers[i];
        }
        System.out.println(“Sum of the entered numbers: ” + sum);
    }
}

Output:

Enter 5 integers:

Enter number 1: 4

Enter number 2: 5

Enter number 3: 2

Enter number 4: 1

Enter number 5: 3

Sum of the entered numbers: 15

Explanation:

Declaration and Allocation:

int[] numbers = new int[5];

  • Declares an array named numbers to hold integers.
  • Allocates memory for an array of size 5.

Input Values into the Array: Uses a for loop to take input from the user for each element in the array.

Calculate and Print Sum: Uses a for loop to calculate sum of elements of the integer array.

6. Answer the following questions:

a. What is a package? What is the default package name used in Java? What is the difference between the two import statement given below:

import java.util.*;

import java.util.Scanner;

Ans: A package in Java is a way to organize related classes and interfaces into a single unit. It helps in avoiding naming conflicts, provides access protection, and supports modularization of code. Packages are used to group related classes and make the code more manageable.

In Java, two packages java.lang package and a no-name package (also called default package) are imported by default in all the classes of Java. Default Package doesn’t have a name but it is present by default and thus, it is named the default package. Java Virtual Machine imports these packages by default in Java internally.

The default package in Java doesn’t have a name and is a collection of classes whose source files do not contain a package declaration. When we don’t mention package declaration and directly create a class it is placed in the default package or no-name package of Java. This default package is also imported along with java.lang every time a java class file is created.

Difference:

import java.util.*;

  • This statement imports all classes and interfaces from the java.util package. The asterisk (*) is a wildcard character, representing all classes and interfaces in the specified package.
  • This is convenient when we need multiple classes from the same package, as it saves us from writing individual import statements for each class.

import java.util.Scanner;

  • This statement imports only the Scanner class from the java.util package.
  • This is useful when we know exactly which class we need from a package, and we want to avoid importing unnecessary classes, which can potentially lead to naming conflicts.

b. What is the difference between the super class and the sub class? What is the use of super class and sub class?

Ans: In object-oriented programming, in the context of inheritance, classes are organized in a hierarchy where we have a superclass (or base class) and one or more subclasses (or derived classes).

Here are the key differences between a superclass and a subclass:

Superclass:

Definition: The superclass is the class from which another class (subclass) inherits properties and behaviors.It is also known as the base class or parent class.

Features:

  • Contains common attributes and behaviors that are shared by its subclasses.
  • Typically represents a more general or abstract concept.

Use:

  • Provides a blueprint for the subclasses to reuse and extend.
  • Encapsulates common functionality to avoid redundancy and promote code reuse.
  • May have abstract methods or concrete methods that can be overridden by subclasses.

Example:

// Superclass

class Shape {

    void draw() {

        System.out.println(“Drawing a shape.”);

    }

}

Subclass:

Definition: The subclass is a class that inherits from another class (superclass). It is also known as the derived class or child class.

Features:

  • Inherits attributes and behaviors from its superclass.
  • Can add additional attributes and behaviors or override existing ones.

Use:

  • Specializes or extends the functionality of the superclass.
  • Reuses the code of the superclass and can customize or enhance it.

Example:

// Subclass

class Circle extends Shape {

    @Override

    void draw() {

        System.out.println(“Drawing a circle.”);

    }

    void calculateArea() {

        System.out.println(“Calculating the area of a circle.”);

    }

}

Use of Superclass and Subclass:

Code Reusability: Superclass provides a common set of features that can be reused by its subclasses, reducing redundancy and promoting maintainability.

Inheritance: Subclass inherits the properties and behaviors of the superclass, allowing for the extension and specialization of functionality.

Polymorphism: Subclass objects can be treated as objects of the superclass, enabling polymorphic behavior.

Organizing code: Superclasses and subclasses help in organizing code in a hierarchical manner, making it more modular and easier to understand.

Abstraction: Superclasses often represent abstract concepts, and subclasses provide concrete implementations, contributing to the abstraction of the system.

c. Explain the concept of Multilevel Inheritance using suitable Java Program.

Ans: Multilevel inheritance is a type of inheritance in object-oriented programming where a class inherits from another class, and then another class inherits from the derived class. This forms a chain of inheritance where each class inherits from the class preceding it. In simple terms, it involves a chain of inheritance with multiple levels.

Programming Example:

// Base class
class Animal {
    void eat() {
        System.out.println(“This animal eats food.”);
    }
}

// Intermediate class inheriting from Animal
class Mammal extends Animal {
    void run() {
        System.out.println(“This mammal can run.”);
    }
}

// Derived class inheriting from Mammal
class Dog extends Mammal {
    void bark() {
        System.out.println(“This dog can bark.”);
    }
}

public class MultilevelInheritance {
    public static void main(String[] args) {
        Dog myDog = new Dog();

        // Accessing methods from different levels of inheritance
        myDog.eat(); // Inherited from Animal
        myDog.run(); // Inherited from Mammal
        myDog.bark(); // Specific to Dogclass

    }
}

In this example:

  • Animal is the base class with a method eat.
  • Mammal is a derived class that extends Animal and adds a method run.
  • Dog is a derived class that extends Mammal and adds a method bark.

When we create an instance of the Dog class, it inherits methods from both the Mammal and Animal classes due to multilevel inheritance. The Dog class can access the eat method from the Animal class, the run method from the Mammal class, and its own method bark.

d. Explain the use of static keyword in the below line.

public static void main (String args[])

{

}

Ans: The static keyword is used for the main method to allow it to be called without creating an instance of the class. The main method is the starting point of a Java program, and it needs to be accessible at the class level, not tied to any specific instance. The static keyword ensures that the method is available to be called at the class level, even before any objects of the class are created.

The main must always be declared as static since the interpreter uses this method before any objects are created. The static keyword is used in the main method to make it a class-level method that can be called without creating an instance of the class. This is essential for the JVM to invoke the main method to start the execution of the Java program.

7. Answer the following questions.

a. What is a byte code? What is the use of byte code in Java Program?

Ans: Bytecode in Java refers to the intermediate code generated by the Java compiler. It is a set of instructions that is designed to be executed by a virtual machine. When we write a Java program, the source code (.java files) is first compiled into bytecode (.class files) by the Java compiler.

When we compile Java source code file, it gets translated into an intermediate code that is called byte code. This byte code is not specific to any particular hardware or operating system.

Uses of bytecode in Java:

Bytecode is a crucial part of Java’s design philosophy, enabling platform independence, security, and dynamic execution.

Platform Independence: The use of bytecode in Java provides a level of abstraction between the compiled Java program and the underlying hardware. This bytecode can be executed on any system that has a java Virtual machine (JVM) installed, allowing Java program to be platform independent.

Security: Bytecode is not machine code, so it cannot be directly executed by the computer. This adds a level of security by preventing direct execution of potentially harmful code. Instead, bytecode is executed within the controlled environment of the JVM.

Dynamic Loading: Bytecode allows for dynamic class loading. Classes can be loaded into the JVM as needed during program execution, providing flexibility in managing resources.

b. What is an interface? Explain interface with a suitable Java Program.

Ans: An interface in Java is a collection of abstract methods. It defines a contract for classes that implement it, specifying a set of methods that must be implemented by any class that adheres to the interface. In addition to abstract methods, an interface can also include constants and default methods (methods with a default implementation).

Here’s a simple example of an interface and a class that implements it:

// Defining an interface named MyInterface

interface MyInterface {

 // Abstract method (implicitly public and abstract)

  void display();

// Constant (implicitly public, static, and final)

   String INTERFACE_NAME = “MyInterface”;

    }

// Implementing the interface in a class

class MyClass implements MyInterface {

 // Implementing the abstract method

    @Override

    public void display() {

        System.out.println(“Implementation of display() in MyClass”);

    }

}

// Main class to demonstrate interface usage

public class InterfaceExample {

    public static void main(String[] args) {

        // Creating an instance of MyClass

        MyClass myObject = new MyClass();

// Calling the implemented method

        myObject.display();

// Accessing the constant from the interface

        System.out.println(“Interface Name: ” + MyInterface.INTERFACE_NAME);

}

}

In this example:

  • MyInterface is an interface with an abstract method display(), and a constant INTERFACE_NAME.
  • MyClass implements MyInterface and provides an implementation for the display() method.
  • The InterfaceExample class demonstrates creating an instance of MyClass, calling the implemented method, accessing the constant, and calling the default method.

c. What are the rules of an abstract class?

Ans: An abstract class in object-oriented programming (OOP) is a class that cannot be instantiated on its own and may contain abstract methods, which are methods without a defined implementation. Abstract classes are meant to serve as blueprints for other classes, providing a common interface and structure for their subclasses.

Here are some rules and characteristics of abstract classes:

Abstract classes in Java have certain rules and characteristics that define their behavior.

Cannot be instantiated: We cannot create an instance (object) of an abstract class directly. Abstract classes are meant to be subclassed by other classes.

May contain abstract methods: Abstract classes can have abstract methods, which are declared without providing an implementation. Subclasses must provide concrete implementations for these abstract methods.

May contain concrete methods: Abstract classes can also have regular (concrete) methods with an implementation. Subclasses inherit these methods but can override them if needed.

Can contain constructors: Abstract classes can have constructors. These constructors are typically used to initialize the common properties of the abstract class.

Can contain fields (variables): Abstract classes can have instance variables, just like regular classes. These fields are often used to store common data that may be shared among subclasses. These fields may be private, protected or public, depending on the design.

Cannot be marked as final: An abstract class cannot be marked as final because the purpose of an abstract class is to be subclassed. A final class cannot be subclassed.

May Extend Another Class (Abstract or Concrete): An abstract class can extend another abstract or non-abstract class.

Subclasses Must Implement Abstract Methods: If a subclass of an abstract class does not provide concrete implementations for all the abstract methods defined in its abstract superclass, it must also be declared as abstract.

d. Define the term encapsulation. Give an example of encapsulation.

Ans: Encapsulation is one of the fundamental principles of object-oriented programming (OOP). It refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit known as a class. The internal details of a class are hidden from the outside world, and access the data is typically controlled through methods.

Encapsulation helps in achieving information hiding, data abstraction, and modularization, making it easier to manage and maintain code. It also allows the internal representation of an object to be hidden from the outside, providing a clear separation between the object’s interface and its implementation.

Key principles of Encapsulation:

Data Hiding: It involves making the fields of a class private and providing access to the fields via public methods. This way, the internal state of the object is not directly accessible from outside the class.

Access Control: Using access modifiers (e.g., private, public, protected), we can control the visibility of classes, fields, and methods. Private members are only accessible within the class, protecting them from external interference.

Example of Encapsulation in Java:

The example will focus on accessing variables with different access modifiers.

class MyClass {
   public int x = 20;
    protected int y = 10;
    private int z = 30;
}
 public class HelloWorld extends MyClass {
      public static void main(String[] args) {
          MyClass obj = new MyClass(); // create class’s object
          System.out.println(obj.x); // printing public variable
          System.out.println(obj.y); // printing protected variable
     }
}

Output:

20

10

This worked fine because variable x is public. The protected variable y will also come through because we inherited the other class (and both classes are in the same package). But when we directly access private variable z, it not worked, will result error. This is because only elements of the class itself can access private variables.

public class Hello extends MyClass {
    public static void main(String[] args) {
    MyClass obj = new MyClass(); // create class’s object
    System.out.println(obj.z); // trying to directly access private variable — will result in error

}

}

Leave a Comment