QB

Sample Questions .pdf


Q1. Write separate programs that shows the implementation of (i)static variable and static member function

Static Variable: In Java, a static variable is shared among all instances of a class. It belongs to the class rather than any individual object. This means that all instances of the class share the same static variable.

Example Program:

class Counter {
    // Static variable
    static int count = 0;

    // Constructor
    Counter() {
        count++;
    }

    // Method to display the count
    void displayCount() {
        System.out.println("Count: " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        Counter obj1 = new Counter();
        Counter obj2 = new Counter();
        Counter obj3 = new Counter();

        // Display count for each object
        obj1.displayCount(); // Output: Count: 3
        obj2.displayCount(); // Output: Count: 3
        obj3.displayCount(); // Output: Count: 3
    }
}

Static Member Function: A static member function (or method) belongs to the class rather than any specific instance. It can be called without creating an instance of the class. Static methods can only directly access static variables and other static methods.

Example Program:

// Java program to demonstrate the use of static member function
class MathUtils {
    // Static method
    static int square(int number) {
        return number * number;
    }

    // Non-static method
    int cube(int number) {
        return number * number * number;
    }
}

public class Main {
    public static void main(String[] args) {
        // Call static method directly using the class name
        int result1 = MathUtils.square(5);
        System.out.println("Square of 5: " + result1); // Output: Square of 5: 25

        // Call non-static method using an instance of the class
        MathUtils mathUtils = new MathUtils();
        int result2 = mathUtils.cube(3);
        System.out.println("Cube of 3: " + result2); // Output: Cube of 3: 27
    }
}

https://youtu.be/zySudOTN05I

(ii)static block concept

A static block in Java is used to initialize static variables when the class is loaded. It is executed only once when the class is first loaded into memory, and it is useful for performing initialization that is more complex than simple assignments.

Example Program 1: Basic Usage of Static Block

In this example, we'll demonstrate how a static block can be used to initialize static variables and perform setup tasks.

class Mobile{
	String brand;
	int price;
	String network;
	static String name;
	
	static {
		name="Phone";
		System.out.println("in static block");
	}
	
	public Mobile() {
		brand="";
		price=200;
//		name="Phone";
		System.out.println("in constructor");
	}
	
	public void show() {
		System.out.println(brand+" : "+price+" : "+name);
	}
}

public class Demo {
	public static void main(String[] args) throws ClassNotFoundException
	{
		Class.forName("Mobile");
		Mobile obj1=new Mobile();
		Class.forName("Mobile");
		Mobile obj2=new Mobile();
	}
}

Q2. Write a program for the addition, subtraction, multiplication and division of two numbers using constructor

class Calculator {
    // Instance variables
    private int num1;
    private int num2;

    // Constructor to initialize the numbers
    public Calculator(int num1, int num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public int add() {
        return num1 + num2;
    }

    public int subtract() {
        return num1 - num2;
    }

    public int multiply() {
        return num1 * num2;
    }

    public int divide() {
        return num1 / num2;
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating an instance of Calculator with two integers
        Calculator calc = new Calculator(10, 5);

        // Performing and displaying the results of various operations
        System.out.println("Addition: " + calc.add());          // Output: Addition: 15
        System.out.println("Subtraction: " + calc.subtract());    // Output: Subtraction: 5
        System.out.println("Multiplication: " + calc.multiply()); // Output: Multiplication: 50
        System.out.println("Division: " + calc.divide());         // Output: Division: 2
    }
}


Q3. Wrapper Class

Need of Wrapper Classes

There are certain needs for using the Wrapper class in Java as mentioned below:

  1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
  2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
  4. An object is needed to support synchronization in multithreading.

Example

public class WrapperExample {
    public static void main(String[] args) {
        // Boxing: Converting primitive to wrapper class
        int primitiveInt = 5;
        Integer wrapperInt = Integer.valueOf(primitiveInt); // Boxing
        System.out.println("Wrapper Integer: " + wrapperInt);

        // Unboxing: Converting wrapper class back to primitive
        Integer anotherWrapperInt = 10;
        int anotherPrimitiveInt = anotherWrapperInt; // Unboxing
        System.out.println("Primitive int: " + anotherPrimitiveInt);
    }
}

<aside> 💡 Purpose of Wrapper Classes

  1. Object Manipulation:
  2. Utility Methods:
  3. Autoboxing and Unboxing:

Q4. Methods available under String and String Buffer Class

String Class

The String class in Java represents immutable sequences of characters. Once a String object is created, its value cannot be changed. Here are some commonly used methods in the String class:

  1. length(): Returns the length of the string.

    javaCopy code
    String str = "Hello";
    int len = str.length(); // len = 5
    
    
  2. charAt(int index): Returns the character at the specified index.

    javaCopy code
    char ch = str.charAt(1); // ch = 'e'
    
    
  3. substring(int beginIndex, int endIndex): Returns a new string that is a substring of the original string.

    javaCopy code
    String sub = str.substring(1, 4); // sub = "ell"
    
    
  4. toLowerCase(): Returns a new string with all characters converted to lowercase.

    javaCopy code
    String lower = str.toLowerCase(); // lower = "hello"
    
    
  5. toUpperCase(): Returns a new string with all characters converted to uppercase.

    javaCopy code
    String upper = str.toUpperCase(); // upper = "HELLO"
    
    
  6. trim(): Removes leading and trailing whitespace from the string.

    javaCopy code
    String spaced = "   Hello   ";
    String trimmed = spaced.trim(); // trimmed = "Hello"
    
    
  7. replace(CharSequence target, CharSequence replacement): Returns a new string with all occurrences of the target sequence replaced by the replacement sequence.

    javaCopy code
    String replaced = str.replace("l", "L"); // replaced = "HeLLo"
    
    
  8. indexOf(String str): Returns the index of the first occurrence of the specified substring.

    javaCopy code
    int index = str.indexOf("l"); // index = 2
    
    
  9. equals(Object obj): Compares the string to the specified object for equality.

    javaCopy code
    boolean isEqual = str.equals("Hello"); // isEqual = true
    
    
  10. split(String regex): Splits the string into an array of substrings based on the specified regular expression.

    javaCopy code
    String[] parts = str.split("l"); // parts = ["He", "", "o"]
    
    

StringBuffer Class

The StringBuffer class represents a mutable sequence of characters. Unlike String, a StringBuffer object can be modified after creation. Here are some commonly used methods in the StringBuffer class:

  1. append(String str): Appends the specified string to the end of the StringBuffer.

    javaCopy code
    StringBuffer sb = new StringBuffer("Hello");
    sb.append(" World"); // sb = "Hello World"
    
    
  2. insert(int offset, String str): Inserts the specified string at the specified position.

    javaCopy code
    sb.insert(5, " Java"); // sb = "Hello Java World"
    
    
  3. delete(int start, int end): Deletes the characters between the specified start and end indices.

    javaCopy code
    sb.delete(5, 10); // sb = "Hello World"
    
    
  4. replace(int start, int end, String str): Replaces the characters between the specified start and end indices with the specified string.

    javaCopy code
    sb.replace(6, 11, "Java"); // sb = "Hello Java"
    
    
  5. reverse(): Reverses the sequence of characters in the StringBuffer.

    javaCopy code
    sb.reverse(); // sb = "avaJ olleH"
    
    
  6. toString(): Converts the StringBuffer to a String.

    javaCopy code
    String str = sb.toString(); // str = "avaJ olleH"
    
    
  7. capacity(): Returns the current capacity of the StringBuffer.

    javaCopy code
    int cap = sb.capacity(); // Returns the capacity of the StringBuffer
    
    
  8. length(): Returns the length of the character sequence currently represented by the StringBuffer.

    javaCopy code
    int len = sb.length(); // Returns the length of the StringBuffer
    
    

Q5. Write a program that shows the use of default, parameterized and copy constructors.

// Class with different types of constructors
class Person {
    // Instance variables
    private String name;
    private int age;

    // Default constructor
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }

    // Parameterized constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Copy constructor
    public Person(Person other) {
        this.name = other.name;
        this.age = other.age;
    }

    // Method to display the person's details
    public void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        // Using the default constructor
        Person person1 = new Person();
        person1.display(); // Output: Name: Unknown, Age: 0

        // Using the parameterized constructor
        Person person2 = new Person("Alice", 30);
        person2.display(); // Output: Name: Alice, Age: 30

        // Using the copy constructor
        Person person3 = new Person(person2);
        person3.display(); // Output: Name: Alice, Age: 30
    }
}


Q6. What is the use of super keyword?

class Parent {
    void display() {
        System.out.println("Parent class display()");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // Calls the display() method of Parent class
        System.out.println("Child class display()");
    }
}

Q8. Differentiate between overloading and overriding

image.png