OOPS with JAVA

Brief Answer Question

1.Bytecode is a low level representation of java code consisting of series of information that helps JVM to execute the code

2. Break is a jumping statement which helps to terminate the loop and continue is also a jumping statement which helps to skip the current iteration.

3. The associativity of operators determines the direction in which an expression is evaluated. 

4. The two dimensional array in java can be declared as follow: int[][] a = new a[2][3];

5. Constructor is a crucial concept in java that help us to declare object, parameterization and customization.

6. Garbage collection in java is a concept where unused reference of object is destroyed to free the memory space occupied by the object.

7. Dynamic Method Dispatch in Java is the process by which a call to an overridden method us resolved at runtime.

8. final is the keyword which is used before the variable to make constant the value of variable and finally is block which is used in exception handling that prints any statement repeatedly.

9. Wildcards are special characters that can stand in for unknown characters in a text value and are handy for locating multiple items with similar, but not identical data.

10. The process of converting the primitive data types into wrapper class types is known as autoboxing

Short Answer Questions

11.Write a program to demonstrate the use of logical OR, AND, and NOT operator with
suitable example.

public class LogicalOpe {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 30;

        //Example of AND operator
        System.out.println(a>b && a>c); //it prints false because both conditions are false
        System.out.println(b>a && b>c);//it prints false because one condition is false
        System.out.println(c>a && c>b);// it prints true because both conditions are true

        //Example of OR operator
        System.out.println(a>b || a>c); //it prints false because both conditions are false
        System.out.println(b>a || b>c);//it prints true because one condition is true
        System.out.println(c>a || c>b);// it prints true because both conditions are true

        //Example of NOT operator
        System.out.println(!(a>b));//it prints true because we know the condition is false but the not operator change the output

    }
}

12.Write a java program to find the second largest element in an array.

import java.util.Scanner;
public class SecondLargest {
    public static void main(String[] args){
       Scanner sc = new Scanner (System.in); 
        int i,j,b;
        System.out.print("Enter the size of array:");
        b = sc.nextInt();
        int arr[] = new int[b];
        for(i=0; i<b; i++){
            System.out.println("Enter "+i+" number:");
            arr[i]=sc.nextInt();
        }
        
        int temp;
        for(i=0; i<b; i++){
            for(j=i+1; j<b; j++){
                if(arr[i]<arr[j]){
                    temp= arr[i];
                    arr[i]= arr[j];
                    arr[j]= temp;
                }
            }
        }
        System.out.println("The second largest number is:"+arr[1]);
    }
    
}

13.Write a java program to illustrate the concepts of method overloading.

 class Boy{
    String name;
    String address;
    int age;
    double weight;

    public void persondetail(String name,String address)
    {
        System.out.println("Name is: "+this.name);
        System.out.println(this.name+" Address is: "+this.address);
    }
    
    public void persondetail(int age)
    {
        System.out.println(this.name+" Age is: "+this.age);
    }
    public void persondetail(double weight)
    {
        System.out.println(this.name+" Weight is: "+this.weight);
    }

}

 public class MethodOverloading{
    public static void main(String[] args) {
        Boy p1 = new Boy();
        p1.name ="Dipesh";
        p1.address ="Parwanipur";
        p1.persondetail(p1.name,p1.address);
    }

 }

14.Write a program by using generic method to swap the positions of two different
elements in an array

public class SwapUsingGenerics{
    public static <T> void swap(T[] array, int a, int b){
        T temp = array[a];
        array[a] = array[b];
        array[b] = temp;
    }
    public static void main(String[] args) {
        Integer[] a ={10,50};
        System.out.println("Before swapping:");
        System.out.println("First number: " + a[0]);
        System.out.println("Second number: " + a[1]);
        System.out.println("******************************");
        swap(a,0, 1);
        System.out.println("After swapping:");
        System.out.println("First number: " + a[0]);
        System.out.println("Second number: " + a[1]);

    }
}

15.Write a java program to find the factorial of any positive integer given by user using
recursion

import java.util.Scanner;
public class FactorialRecursion {
   public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
       int a,b;
       System.out.println("Enter number:");
       a=sc.nextInt();
       b=recursion(a);
       System.out.println("Factorial is:"+b);
   }
   static int recursion(int a){
        if(a==0)
            return 0;
        
        else
            return (a*recursion(a-1));
        
            
        
}
}

16. Explain for-each statement with suitable example.

In Java, the “for-each” loop is a specialized loop designed for iterating over elements in arrays, collections, or other iterable data structures. It provides a more concise and readable way to iterate through these elements compared to traditional “for” or “while” loops. The for-each loop is also known as the “enhanced for loop” or the “foreach loop.”

we can understand with the help of following code:

import java.io.*;
  
class Easy
  
{
  
    public static void main(String[] args)
  
    {
  
        // array declaration
  
        int ar[] = { 10, 40, 60, 70, 100 };
  
        for (int element : ar)
  
            System.out.print(element + " ");
    }
}

Long Answer Questions

  1. Create a Shape interface having methods area() and perimeter(). Create two
    subclasses, Circle and Rectangle that implement the Shape interface. Create a class
    Sample with main method and demonstrate the area and perimeters of both the shape
    classes. You need to handle the values of length, breath, and radius in respective
    classes to calculate their area and perimeter.
// Shape interface
interface Shape {
    double area();
    double perimeter();
}

// Circle class
class Circle implements Shape {
    private double radius;

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

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

    @Override
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}

// Rectangle class
class Rectangle implements Shape {
    private double length;
    private double breadth;

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

    @Override
    public double area() {
        return length * breadth;
    }

    @Override
    public double perimeter() {
        return 2 * (length + breadth);
    }
}

// Sample class
public class Sample {
    public static void main(String[] args) {
        // Create a circle with radius 5
        Circle circle = new Circle(5);
        System.out.println("Circle area: " + circle.area());
        System.out.println("Circle perimeter: " + circle.perimeter());

        // Create a rectangle with length 4 and breadth 6
        Rectangle rectangle = new Rectangle(4, 6);
        System.out.println("Rectangle area: " + rectangle.area());
        System.out.println("Rectangle perimeter: " + rectangle.perimeter());
    }
}
  1. Create a class Student with private member variables name and percentage. Write
    methods to set, display, and return values of private member variables in the Student
    class. Create 10 different objects of the Student class, set the values, and display name
    of the Student who have highest average_marks in the main method of another class
    named StudentDemo

class Student{
    private String name;
    private double percentage;

    public Student(String name, double percentage){
        this.name = name;
        this.percentage = percentage;
    }
    public void setname(String name){
        this.name = name;     
    }
    public String getName() {
        return name;
    }
    public void setpercentage(double percentage){
        this.percentage = percentage;
    }
    public double getPercentage() {
        return percentage;
    }
    public void display(){
        System.out.println("Name: "+name);
        System.out.println("Percentage: "+percentage);
    }
    
    
}
public class ModelQue {
    public static void main(String[] args) {
        Student[] student =new Student[10];
        student[0] = new Student("Student1", 85.5);
        student[1] = new Student("Student2",88.7);
        student[2] = new Student("Student3",90.8);
        student[3] = new Student("Student4",80.3);
        student[4] = new Student("Student5", 85.5);
        student[5] = new Student("Student6",88.7);
        student[6] = new Student("Student7",40.8);
        student[7] = new Student("Student8",70.3);
        student[8] = new Student("Student9",50.8);
        student[9] = new Student("Student10",60.3);
        double maxAverage = 0.0;
        String highestAverageStudentName = "";

        for (Student students : student) {
            if (students.getPercentage() > maxAverage) {
                maxAverage = students.getPercentage();
                highestAverageStudentName = students.getName();
            }
        }

        
        System.out.println("Student with the highest average percentage: " + highestAverageStudentName);
}
}
  1. Differentiate between Checked and Unchecked Exceptions. Write a program to
    illustrate the concept of ArrayIndexOutOfBoundException

This is the example of unchecked exception:

public class Unchecked {
    public static void main(String[] args) {
        int arr[] = {1,2,3,4,5,6,7};
        try{
            for(int i=0; i <= 7; ++i){
        System.out.println(arr[i]);
       }
        }
        catch(ArrayIndexOutOfBoundsException ex){
            System.out.println("Array limit is overpassed");
        }
        finally{
            System.out.println("Thank You !!");
        }
       int a = 10;
       int b = 0;
       try{
                int c = a / b;//This one is mathematically incorrect
       }
       catch(ArithmeticException ex){
        System.out.println("Not divided by zero.........");
       }
        
    }
}

This is the example of checked excption:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            
            FileReader fileReader = new FileReader("example.txt");
            
            
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            
            
            String line = bufferedReader.readLine();
            
            
            bufferedReader.close();
            
     
            System.out.println("Line from file: " + line);
        } catch (IOException e) {
   
            System.err.println("An IOException occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

  1. Write a Java program to read data from the file “text.txt” and write the data into the
    file “best.txt”
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.IOException;

class ReadndWrite {
    public static void main(String[] args) {
        File file = new File("text.txt");
        String line;

        try {
            Scanner sc = new Scanner(file);
            FileWriter filewriter = new FileWriter("best.txt"); // Create an output file for writing

            while (sc.hasNextLine()) {
                line = sc.nextLine();
                System.out.println(line);

                // Write the current line to the output file
                filewriter.write(line + "\n"); // Add a newline character to separate lines
            
            }

            // Close the FileWriter when done writing
            filewriter.close();
        } catch (IOException ex) {
            System.out.println("Error !!");
        }
        
    }
}

Comprehensive Questions

20.Explain the OOP principal followed by Java. What are the restrictions when the
method is declared as static? Write a java program to illustrate the concepts of static
method.

Java is an object-oriented programming (OOP) language, and it follows several key OOP principles, including:

  1. Encapsulation: Java supports encapsulation by allowing you to define classes that hide their internal details (data) and expose a well-defined interface (methods) to interact with that data. You can use access modifiers like private, protected, and public to control the visibility of class members.
  2. Inheritance: Java supports inheritance, allowing you to create new classes (subclasses or derived classes) based on existing classes (superclasses or base classes). Inheritance promotes code reuse and the creation of class hierarchies.
  3. Polymorphism: Polymorphism is supported in Java through method overriding and interfaces. Method overriding allows a subclass to provide a specific implementation of a method defined in its superclass. Interfaces enable multiple classes to implement the same methods, allowing for different implementations.
  4. Abstraction: Abstraction is the process of simplifying complex systems by modeling classes with relevant attributes and methods while hiding unnecessary details. In Java, abstract classes and interfaces are used to define abstract types, which cannot be instantiated directly but can be extended or implemented by concrete classes.
  5. Association, Aggregation, and Composition: Java supports relationships between classes through associations, aggregations, and compositions. These relationships allow one class to be related to another, either by reference or ownership.

Regarding your question about static methods, here are some key points and restrictions when a method is declared as static in Java:

  1. Static Method Definition: A static method belongs to the class itself rather than to an instance of the class. It is associated with the class, not with any specific object created from the class.
  2. No Access to Instance Variables: Inside a static method, you cannot directly access instance variables (non-static fields) of the class. Static methods can only access other static members of the class.
  3. Can Be Called on Class: Static methods can be called on the class itself, rather than on an instance of the class. You don’t need to create an object to invoke a static method.
  4. Common Use Cases: Static methods are often used for utility functions, helper methods, or factory methods that don’t depend on instance-specific data.
  5. Can’t Override: Static methods cannot be overridden in subclasses because they are associated with the class itself, not with instances of the class.

Here’s a Java program illustrating the concept of a static method:

public class StaticMethodExample { 

// Static method that calculates the square of a number 

public static int square(int num)

 { return num * num; }

 public static void main(String[] args)

 { 

int x = 5; 

int result = square(x); // Calling the static method directly System.out.println("Square of " + x + " is " + result); } }
  1. What is inheritance? What are the advantages of using inheritance? Explain different
    types of inheritance with example of each.

Inheritance is one of the fundamental concepts of object-oriented programming (OOP) that allows you to create a new class based on an existing class. Inheritance enables a class to inherit the properties (fields) and behaviors (methods) of another class, known as the superclass or base class. The new class is called a subclass or derived class. In essence, the subclass is a specialized version of the superclass.

Advantages of Using Inheritance:

  1. Code Reusability: Inheritance promotes code reuse because a subclass inherits the attributes and behaviors of the superclass. You don’t have to rewrite the same code in multiple places.
  2. Modularity: Inheritance helps in breaking down complex systems into smaller, manageable parts (classes). You can create a hierarchy of related classes, each responsible for a specific aspect of the system.
  3. Polymorphism: Inheritance supports polymorphism, allowing objects of the subclass to be treated as objects of the superclass. This simplifies code and enables dynamic method invocation through method overriding.
  4. Easier Maintenance: Changes made in the superclass automatically reflect in all its subclasses. This ensures consistency and simplifies maintenance.
  5. Specialization: Subclasses can add new attributes and methods or modify existing ones to customize the behavior of the superclass for specific needs.
  6. Extensibility: You can create new classes based on existing ones, extending the functionality as the application evolves.

Different Types of Inheritance:

  1. Single Inheritance:
    • In single inheritance, a subclass inherits from a single superclass.
    • Java supports single inheritance for classes (but allows multiple inheritance for interfaces).
    • Example:
class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}
class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

Multiple Inheritance (Interface Inheritance):

  • Multiple inheritance allows a subclass to inherit from more than one superclass.
  • Java achieves multiple inheritance through interfaces (a class can implement multiple interfaces).
  • Example:
interface Animal {
    void eat();
}

interface Bird {
    void fly();
}

class Parrot implements Animal, Bird {
    public void eat() {
        System.out.println("Parrot is eating");
    }

    public void fly() {
        System.out.println("Parrot is flying");
    }
}

Multilevel Inheritance:

  • In multilevel inheritance, a subclass inherits from another subclass.
  • Example:
class Grandparent {
    void grandparentMethod() {
        System.out.println("Grandparent's method");
    }
}

class Parent extends Grandparent {
    void parentMethod() {
        System.out.println("Parent's method");
    }
}

class Child extends Parent {
    void childMethod() {
        System.out.println("Child's method");
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *