Java QB M1 M2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

MODULE 1

1) What are the features of object oriented programming language?


 Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects," which can contain data and code to manipulate that data. Here are the main
features of an object-oriented programming language
 Encapsulation – Bundles data and methods within a class, protecting data by restricting
access.
 Abstraction – Hides complex details, showing only essential features to simplify usage.
 Inheritance – Allows one class to inherit properties and behaviors from another, promoting
code reuse.
 Polymorphism – Enables methods to perform differently based on the object's class,
supporting flexibility.
 Classes and Objects – Classes define blueprints, and objects are instances of these classes.
 Dynamic Binding – Delays method binding until runtime, enabling flexibility in
polymorphism.
 Message Passing – Allows objects to communicate by calling each other’s methods for
modular interaction.
2) List and briefly explain the keywords in Java programming language.
 class – Defines a class, which is a blueprint for objects.
 public – An access modifier that makes classes, methods, or variables accessible from any
other class.
 static – Declares a variable or method that belongs to the class itself rather than instances
of the class.
 void – Indicates a method does not return any value.
 int – Declares a 32-bit integer variable.
 if – Starts a conditional statement, executing code if the condition is true.
 else – Runs code if the if condition is false.
 for – Begins a loop that repeats a specific number of times.
 while – Begins a loop that repeats as long as the condition is true.
 return – Exits a method, optionally returning a value.
 new – Creates new instances of objects.
3) What are the primitive data types defined in java programming language?
 byte – 8-bit integer, range: -128 to 127.
 short – 16-bit integer, range: -32,768 to 32,767.
 int – 32-bit integer, range: -2^31 to 2^31 - 1.
 long – 64-bit integer, range: -2^63 to 2^63 - 1 (suffix "L").
 float – 32-bit floating-point, for decimals (suffix "F").
 double – 64-bit floating-point, default for decimals.
 char – 16-bit Unicode character, stores single characters.
 boolean – Represents true or false.
4) Differentiate between type conversion and type casting.
 Type Conversion (Automatic/Implicit)
o Java automatically converts a smaller data type to a larger one (e.g., int to long or
float to double).
o It’s safe, as there’s no loss of data.
o int num = 100;
double d = num; // Automatic conversion from int to double
 Type Casting (Manual/Explicit)
o The programmer explicitly forces a larger data type into a smaller one (e.g., double
to int).
o It may lead to data loss and needs to be done carefully.
o double d = 9.8;
int num = (int) d; // Explicit casting from double to int, fractional part is loss.
5) List and explain java buzzwords with suitable examples.
 Simple – Easy to learn and use, with syntax similar to C++ but without complex features like
pointers.
 Object-Oriented – Organizes code around objects and classes to model real-world concepts.
 Platform-Independent – Compiled bytecode can run on any system with a JVM.
 Secure – Built-in security features like bytecode verification and sandboxing protect against
malicious code.
 Multithreaded – Supports multiple threads within a program, enhancing performance in
concurrent applications.
 High Performance – JIT compiler optimizes bytecode at runtime, improving execution speed.
 Dynamic – Supports runtime loading and linking of classes, enabling flexible, adaptive
behavior.
6) How to declare and accept values for two dimensional arrays in Java. Explain with a suitable
example.
 In Java, a two-dimensional array can be declared and initialized as an array of arrays
o dataType[][] arrayName = new dataType[rows][columns];
o int[][] matrix = new int[3][3];

import java.util.Scanner;
public class TwoDArrayExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Declare a 2D array with 3 rows and 3 columns
int[][] matrix = new int[3][3];
// Accept values for the array
System.out.println("Enter values for a 3x3 matrix:");
for (int i = 0; i < 3; i++) { // Loop over rows
for (int j = 0; j < 3; j++) { // Loop over columns
System.out.print("Enter value for matrix[" + i + "][" + j + "]: ");
matrix[i][j] = scanner.nextInt(); // Accept input for each element
}
}

// Display the 2D array


System.out.println("The 3x3 matrix is:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
7) Can ternary operator be replaced by nested if statements? Justify your answer with an
example.
 Yes, a ternary operator can be replaced by nested if statements, though it may make the
code longer and less concise. The ternary operator is used as a shorthand for if-else
statements to assign values based on a condition. It is typically preferred when you have
simple conditions and want to make the code concise.
o variable = (condition) ? value_if_true : value_if_false;
o if (condition) {
variable = value_if_true;
} else {
variable = value_if_false;
}
 Use Case: The ternary operator is best suited for simple conditions with a single assignment.
For complex decision-making (multiple branches or nested conditions), nested if statements
are usually more readable.
8) Are the below statement valid?
a) for ( ; ; )
b) for( int a:arr[])
 The first statement is valid and it is an infinite for loop, and it will execute infinite loop until
explicitly out of break statement
o for ( ; ; ) {
System.out.println("This is an infinite loop.");
break; // You can add a break to stop the loop
}
 The second statement is not true and it also attempts for a for each loop to iterate over in
an array
 It is not valid due to the invalid syntax
o int[] arr = {1, 2, 3};
for (int a : arr) {
System.out.println(a);
}
9) Write a java program to calculate the average among the elements {8, 6, 2, 7} using for each
looping? How for each is different from for loop?
public class AverageCalculator {
public static void main(String[] args) {
int[] numbers = {8, 6, 2, 7};
int sum = 0;

// Using for-each loop to calculate the sum


for (int number : numbers) {
sum += number;
}

// Calculating the average


double average = (double) sum / numbers.length;
System.out.println("The average is: " + average);
}
}
10) Explain the operations of the following operators with example for each
a) >>> b) && c) >>
 >>> - Unsigned right shidt operator
o The >>> operator shifts bits to the right, filling the leftmost bits with 0 regardless of the
sign. This is called an unsigned right shift, as it doesn’t preserve the sign bit (leftmost bit)
of the number.
o int num = -8; // Binary: 11111111 11111111 11111111 11111000
int result = num >>> 2; // Shift right by 2, filling left bits with 0
System.out.println(result); // Output: 107374182
 && - Logical AND operator
o The && operator is a logical AND operator used with boolean values. It returns
true if both conditions are true; otherwise, it returns false. It’s a short-circuit
operator, meaning that if the first condition is false, it does not evaluate the
second condition
o int a = 5;
int b = 10;
if (a > 0 && b > a) {
System.out.println("Both conditions are true.");
} else {
System.out.println("One or both conditions are false.");
}
 >> Right Signed Shift operator
o The >> operator shifts bits to the right, filling the leftmost bits based on the sign
of the number. If the number is positive, 0s are added; if negative, 1s are added.
This is called a signed right shift because it preserves the sign of the number.
o int num = -8; // Binary: 11111111 11111111 11111111 11111000
int result = num >> 2; // Shift right by 2, filling left bits with 1
System.out.println(result); // Output: -2
11) What is the output of the above code? If you insert int b= -1outside for loop. What is the
output?
 Original Code Output: The output is -1 50 -1 50 -1 50 as b is reinitialized to -1 in each
iteration of the loop.
 Modified Code Output: The output is -1 50 50 50 50 50 because b is initialized outside
the loop, retaining the value 50 for subsequent iterations.
12) List and explain different jump statements used in java with an example for each.
 Break – The break statement is used to exit from a loop or a switch statement prematurely.
 public class BreakExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i is 5
}
System.out.print(i + " ");
}
}
}
 Continue – The continue staement skips the current iteration and proceeds to the next
iteration.
 public class ContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skips even numbers
}
System.out.print(i + " ");
}
}
}
 Return – The return ststent is u used to exit from a mothid and optionally retrn it,,,,.
 public class ReturnExample {
public static void main(String[] args) {
System.out.println(getSquare(5)); // Calls the method and prints the result
}

static int getSquare(int num) {


return num * num; // Returns the square of the number
}
}
13) List and explain different iteration statements used in java with an example for each.
 For Loop – The for loop is used when the number of iterations is known beforehadn. It
consists of intitialization, condition, and iteration
o public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // Prints numbers from 0 to 4
}
}
}
 While Loop – The while loop executes a block of code as long as a specified condition is true.
It checks the consdition before eaxh iteration
o public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.print(i + " "); // Prints numbers from 0 to 4
i++;
}
}
}
 Do Whil llop – The do while llop is similar to the while llop but it gurarentees that the block
of code will execute at leat once because the condition is checked after the code block.
o public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 0;
do {
System.out.print(i + " "); // Prints numbers from 0 to 4
i++;
} while (i < 5);
}
}
14) Write a program in java to implement a stack operation that can hold 10 integers.
import java.util.Scanner;
class SimpleStack {
private int[] stack = new int[10]; // Stack can hold 10 integers
private int top = -1; // Stack is initially empty
public void push(int value) { // Push operation
if (top == 9) { // Check for stack overflow
System.out.println("Stack Overflow! Cannot push " + value);
} else {
stack[++top] = value; // Increment top and add value
System.out.println("Pushed " + value + " to stack.");
}
}

// Pop operation
public int pop() {
if (top == -1) { // Check for stack underflow
System.out.println("Stack Underflow! Cannot pop.");
return -1; // Return -1 for empty stack
} else {
return stack[top--]; // Return top value and decrement top
}
}

// Display the stack


public void display() {
if (top == -1) {
System.out.println("Stack is empty.");
} else {
System.out.print("Stack elements: ");
for (int i = 0; i <= top; i++) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
}
}

public class StackDemo {


public static void main(String[] args) {
SimpleStack stack = new SimpleStack();
Scanner scanner = new Scanner(System.in);
int choice, value;

do {
System.out.println("\n1. Push\n2. Pop\n3. Display\n4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter an integer to push: ");
value = scanner.nextInt();
stack.push(value);
break;
case 2:
int poppedValue = stack.pop();
if (poppedValue != -1) {
System.out.println("Popped " + poppedValue + " from stack.");
}
break;
case 3:
stack.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Please try again.");
}
} while (choice != 4);

scanner.close();
}
}
15) Explain the process of compiling and running java application with an example.
 Write the java code: Create a file named HelloWorld.java
o public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
 Open Command Prompt/Terminal: Navigate to the directory where your .java file is saved.
 Compile the code – javac HelloWorld.java
 Run the Program: Execute the bytecode:
o Java helloWorld
 Output we would see:
o Hello, World!
16) Explain the scope and lifetime of the variable with an example.
 Scope of Variables
o Local Scope: Variables declared within a method or block are accessible only within
that method or block.
public class ScopeExample {
public void method() {
int localVariable = 5; // Local variable
System.out.println("Local Variable: " + localVariable);
}

public void anotherMethod() {


// System.out.println(localVariable); // This will cause a compilation error
}
}

 Instance Scope
o Variables declared within a class but outside any method can be accessed by all
instance methods of the class.
public class InstanceScope {
int instanceVariable = 10; // Instance variable

public void display() {


System.out.println("Instance Variable: " + instanceVariable);
}
}
 Static Scope
o Variables declared as static belong to the class itself and can be accessed without
creating an instance of the class.
public class StaticScope {
static int staticVariable = 15; // Static variable

public static void display() {


System.out.println("Static Variable: " + staticVariable);
}
}
 Lifetime of variables
o Local Variables: The lifetime of local variables is limited to the method or block in
which they are declared. They are created when the method is called and destroyed
when the method exits.
o Instance Variables: The lifetime of instance variables is tied to the lifetime of the
object. They exist as long as the object exists.
o Static Variables: The lifetime of static variables is the entire duration of the program.
They are created when the class is loaded and destroyed when the program
terminates.
o public class ScopeAndLifetime {
static int staticVar = 20; // Static variable
public void method() {
int localVar = 5; // Local variable
System.out.println("Local Variable: " + localVar);
System.out.println("Static Variable: " + staticVar);
}
public static void main(String[] args) {
ScopeAndLifetime obj = new ScopeAndLifetime();
obj.method();
// Accessing static variable without an object
System.out.println("Accessing Static Variable: " + ScopeAndLifetime.staticVar);
// System.out.println(localVar); // This will cause a compilation error
}
}

17) Write a Java program to find the biggest among n numbers using the ternary operator.
import java.util.Scanner;

public class LargestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int biggest = Integer.MIN_VALUE; // Initialize biggest to the smallest integer

System.out.println("Enter " + n + " numbers:");


for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
// Use ternary operator to find the biggest number
biggest = (number > biggest) ? number : biggest;
}

System.out.println("The largest number is: " + biggest);


scanner.close();
}
}
18) Explain class concept in java along with declaration of objects.
 A class is defined using the class keyword followed by the class name. The class can contain
fields (variables) and methods (functions) that define the state and behavior of the objects.
 public class ClassName {
// Fields (attributes)
dataType fieldName;

// Constructor
public ClassName(dataType parameter) {
// Initialize fields
}

// Methods
public returnType methodName(parameters) {
// Method body
}
}
 Classes can use access modifiers (public, private, protected) to control visibility. A public
class is accessible from any other class, while a private class is only accessible within its own
class.

 To create an object from a class, you use the new keyword followed by the class
constructor. The object is an instance of the class and has its own set of values for the fields
defined in the class.
 Car myCar = new Car("Red", "Toyota", 2021);
 myCar.displayDetails(); // Outputs: Car Model: Toyota, Color: Red, Year: 2021
19) Write the attributes and behaviour for the following classes.
A) “car”
B) “Cellphone”
C) “Dress”
D) “Course”
E) “Bank Account”

A) Car

Attributes:

 String color
 String model
 int year
 String make
 int speed

Behaviors:

 void accelerate(): Increases the speed of the car.


 void brake(): Decreases the speed of the car.
 void displayDetails(): Displays the car's details.

B) Cellphone

Attributes:

 String brand
 String model
 String operatingSystem
 int batteryLife
 double screenSize

Behaviors:

 void makeCall(String phoneNumber): Initiates a call to the specified phone number.


 void sendMessage(String phoneNumber, String message): Sends a message to the specified
phone number.
 void displayInfo(): Displays the cellphone's details.
C) Dress

Attributes:

 String color
 String size
 String fabric
 String style
 double price

Behaviors:

 void wear(): Simulates wearing the dress.


 void displayDetails(): Displays details about the dress.
 void alterSize(String newSize): Changes the size of the dress.

D) Course

Attributes:

 String courseName
 String courseCode
 int credits
 String instructor
 List<String> enrolledStudents

Behaviors:

 void enrollStudent(String studentName): Enrolls a student in the course.


 void dropStudent(String studentName): Removes a student from the course.
 void displayCourseInfo(): Displays information about the course.

E) Bank Account

Attributes:

 String accountHolderName
 String accountNumber
 double balance
 String accountType

Behaviors:

 void deposit(double amount): Adds the specified amount to the account balance.
 void withdraw(double amount): Deducts the specified amount from the account balance.
 void displayAccountInfo(): Displays account details and current balance.

20) A class called EMPLOYEE, which models an employee with an id, name and salary. The
method raisesalary (perent) increases the salary by given percentage. Develop an EMPLOYEE
class and suitable main() method for demonstration.
public class EMPLOYEE {
private int id;
private String name;
private double salary;
// Constructor
public EMPLOYEE(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}

// Method to increase salary by a given percentage


public void raiseSalary(double percent) {
salary += salary * (percent / 100);
}

// Method to display employee details


public void displayDetails() {
System.out.println("Employee ID: " + id);
System.out.println("Employee Name: " + name);
System.out.println("Employee Salary: $" + salary);
}

// Main method for demonstration


public static void main(String[] args) {
// Create an EMPLOYEE object
EMPLOYEE emp1 = new EMPLOYEE(101, "John Doe", 50000);

// Display initial details


System.out.println("Initial Employee Details:");
emp1.displayDetails();

// Raise salary by 10%


emp1.raiseSalary(10);

// Display updated details


System.out.println("\nUpdated Employee Details after 10% raise:");
emp1.displayDetails();
}
}

MODULE - 2
21) Explain with example, when constructors are called in class hierarchy.
 In a class hierarchy, constructors are called from the top of the hierarchy downwards,
starting from the superclass and moving to the subclass. This ensures that the superclass is
fully initialized before the subclass’s constructor executes.
 In Java, this happens because each subclass constructor implicitly calls its superclass
constructor using super(), even if not explicitly stated. If a specific superclass constructor
needs to be called, you can use super(parameters) in the subclass constructor.
 class Animal {
// Constructor of superclass
public Animal() {
System.out.println("Animal constructor called");
}
}

class Dog extends Animal {


// Constructor of subclass Dog
public Dog() {
super(); // Implicit call to Animal's constructor
System.out.println("Dog constructor called");
}
}

class Puppy extends Dog {


// Constructor of subclass Puppy
public Puppy() {
super(); // Implicit call to Dog's constructor
System.out.println("Puppy constructor called");
}
}

public class Main {


public static void main(String[] args) {
// Create an instance of Puppy
Puppy myPuppy = new Puppy();
}
}
22) Compare and contrast method overloading and method overriding with a suitable example.

 Method Overloading - Method overloading allows multiple methods in the same class to
have the same name but different parameter lists (either by type or number of parameters).
o Compile time polymorphism
 Method Overriding - Method overriding occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass.
o Run time polymorphism

METHOD OVERLOADING
class MathOperations {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of two numbers: " + math.add(5, 10));
System.out.println("Sum of three numbers: " + math.add(5, 10, 15));
}
}
METHOD OVERRIDING
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Overriding method in subclass
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Polymorphism
myDog.sound(); // Calls Dog's overridden method
}
23) Explain usage of super keyword in Java with suitable examples.
The super keyword in Java is used to refer to the superclass (parent class) of a subclass. It serves
several purposes in object-oriented programming, especially for accessing superclass members
and constructors.
 Key Usages of super in Java
a. Calling Superclass Constructor: super is used to call the constructor of the immediate
superclass. This is especially helpful when the superclass has parameterized constructors
that need to be initialized in the subclass.
b. Accessing Superclass Methods: super allows a subclass to call a method from its
superclass, particularly useful if the method has been overridden in the subclass.
 Calling superclass constructor with super()
c. class Animal {
public Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
public Dog() {
super(); // Calls Animal's constructor
System.out.println("Dog constructor called");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
}
}
 Accessing superclass method with Super.methodname()
class Animal {
public void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
super.sound(); // Calls Animal's sound method
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound();
}
24) Define and explain different types of inheritance in Java
 Single inheritance – a subclass inherits from a single superclass
o class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark();
}
}
 Multilevel Inheritance – A class derived from a subclass which in turn is derived from
another class forming a chain of inheritance
o class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy myPuppy = new Puppy();
myPuppy.eat(); // Inherited from Animal
myPuppy.bark(); // Inherited from Dog
myPuppy.weep();
}
 Hierarchial Inheritance – Multiple classes inherit from the same superclass
o class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}}
class Cat extends Animal {
void meow() {
System.out.println("Meowing...");
}}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();
myDog.eat();
myDog.bark();
myCat.eat();
myCat.meow();
}}
 Multiple Inheritance – A class implements multiple interfaces gaining the ability to use
mthods form the multiple sources
o interface AnimalActions {
void eat();
}
interface Pet {
void cuddle();
}
class Dog implements AnimalActions, Pet {
public void eat() {
System.out.println("Eating...");
}
public void cuddle() {
System.out.println("Cuddling...");
}}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.cuddle();
}
}
25) Explain interfaces in java with example
Interfaces are a way to achieve abstraction and multiple inheritance (indirectly) in Java, and
they define a contract that implementing classes must follow.
Abstract Methods: Interfaces can only have abstract methods by default (methods without a
body). Since Java 8, interfaces can also have default and static methods with a body.
Constants: Variables declared in an interface are public, static, and final by default.
Multiple Inheritance: A class can implement multiple interfaces, overcoming the limitation of
single inheritance in Java.
No Constructor: Interfaces cannot be instantiated, so they don’t have constructors.
// Define an interface
interface Animal {
void sound(); // Abstract method
void eat(); // Another abstract method
}
// Class Dog implements the Animal interface
class Dog implements Animal {
// Implementing the methods defined in the interface
public void sound() {
System.out.println("Dog barks");
}
public void eat() {
System.out.println("Dog eats");
}
}
// Class Cat implements the Animal interface
class Cat implements Animal {
public void sound() {
System.out.println("Cat meows");
}
public void eat() {
System.out.println("Cat eats");
}
}
public class Main {
public static void main(String[] args) {
// Creating instances of Dog and Cat
Animal myDog = new Dog();
Animal myCat = new Cat();
// Calling methods
myDog.sound();
myDog.eat();
myCat.sound();
myCat.eat();
}
}
26) Can interfaces be inherited in java? Justify your answer with an example
 Yes, interfaces can be inherited in Java. This is called interface inheritance, where one
interface can extend one or more other interfaces. When an interface extends another
interface, it inherits all the methods declared in the parent interface(s). This allows the
new interface to add more methods while building on the existing contract.
 // Base interface
interface Animal {
void eat();
}
// Child interface extending Animal
interface Pet extends Animal {
void play();
}
// Dog class implements Pet (and indirectly Animal)
class Dog implements Pet {
public void eat() {
System.out.println("Dog eats");
}
public void play() {
System.out.println("Dog plays");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal through Pet
myDog.play(); // Defined in Pet
}
}
27) Discuss the following terms with an example:
a) Static b) final c) Abstract methods d) Abstract classes
 Static - The static keyword in Java indicates that a particular member (variable or method)
belongs to the class itself, rather than instances of the class. Static members can be
accessed without creating an instance of the class.
o class MyClass {
static int counter = 0; // static variable
static void showCounter() { // static method
System.out.println("Counter: " + counter);
}
}
public class Main {
public static void main(String[] args) {
MyClass.counter = 5; // Accessing static variable
MyClass.showCounter(); // Calling static method
}
 Final - The final keyword in Java is used to create constants, prevent inheritance, or prevent
method overriding. A final variable cannot be modified, a final method cannot be
overridden, and a final class cannot be subclassed.
o final class Constants {
static final double PI = 3.14159; // final variable (constant)
}

public class Main {


public static void main(String[] args) {
System.out.println("Value of PI: " + Constants.PI);
}
}
 Abstract Methods - An abstract method is a method declared without an implementation. It
is meant to be overridden in subclasses. Abstract methods can only exist in abstract classes
or interfaces.
o abstract class Shape {
abstract void draw(); // abstract method
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
}}
 Abstract Classes - An abstract class in Java is a class that cannot be instantiated and may contain
abstract methods. It serves as a blueprint for other classes.
o abstract class Animal {
abstract void sound(); // abstract method
void sleep() {
System.out.println("Animal is sleeping");
}}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
animal.sleep();
}
28) Briefly explain with an example, the role of nested and inner classes in Java.

 Nested Class - A static nested class is associated with its outer class and does not require an
instance of the outer class. It can only access the static members of the outer class directly.
o class OuterClass {
static int outerStaticVar = 10;
// Static nested class
static class StaticNestedClass {
void display() {
System.out.println("Static Nested Class accessing static variable: "
outerStaticVar);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display();
}
}
 Inner Class - An inner class (non-static) is associated with an instance of the outer class, so it
has access to both static and non-static members of the outer class. It requires an instance
of the outer class to be instantiated.
o class OuterClass {
private int outerVar = 20;
// Inner class
class InnerClass {
void display() {
System.out.println("Inner Class accessing instance variable: " + outerVar);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass(); // Create an instance of OuterClass
OuterClass.InnerClass inner = outer.new InnerClass(); // Create an instance of
InnerClass
inner.display();
}
}
 Static Nested Class: Can only access static members of the outer class and does not need an
instance of the outer class.
 Inner Class: Has access to both static and instance members of the outer class and requires
an instance of the outer class.
29) Define constructors in Java. Explain different types of constructors in Java with an example for each.
 In Java, a constructor is a special method used to initialize objects. It has the same name as the
class and no return type. Constructors are called automatically when an object is created, allowing
us to set initial values for object attributes.
 Default Constructer – A default constructer is a constructor with no parameters. If no constructor is
ecplicitly defined in a class, java provides a default constructor automatically.
o class Car {
String brand;
// Default constructor
Car() {
brand = "Toyota";
}
void display() {
System.out.println("Brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car(); // Calls the default constructor
car.display();
}
}
 Parameterized Constructor - A parameterized constructor accepts arguments to
initialize an object with specific values when it’s created. This type of constructor
allows for more flexibility in object creation.
o class Car {
String brand;
int year;
// Parameterized constructor
Car(String b, int y) {
brand = b;
year = y;
}
void display() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Honda", 2020); // Calls the parameterized constructor
car.display();
}
}
30) Write a note on the following: a) Garbage collection b) this keyword c) Access control

 Garbage Collection - Garbage collection is an automatic memory management


process in Java, where unused or unreferenced objects are identified and removed
from memory, freeing up resources.
o public class Main {
public static void main(String[] args) {
Main obj = new Main();
obj = null; // Now eligible for garbage collection
System.gc(); // Requesting JVM to perform garbage collection
}
}
 this Keyord - The this keyword in Java refers to the current instance of the class and
is used to access the class’s fields, methods, and constructors.
o class Car {
String brand;

// Constructor with parameter


Car(String brand) {
this.brand = brand; // "this.brand" refers to the instance variable
}

void display() {
System.out.println("Brand: " + this.brand);
}
}
 Access Control - Access control in Java defines the visibility and accessibility of
classes, methods, and variables. It ensures encapsulation by controlling which parts
of a program can access certain parts of the code.
o class Car {
private String brand; // private - accessible only within Car
protected int year; // protected - accessible in the same package and by
subclasses

public Car(String brand, int year) {


this.brand = brand;
this.year = year;
}

public void displayBrand() { // public - accessible from anywhere


System.out.println("Brand: " + brand);
}
}
31) Can constructors be overloaded? Justify your answer with a program example.

 Yes, constructors can be overloaded in Java. Constructor overloading means having


multiple constructors in a class with different parameter lists. Each constructor can
be used to initialize the object in different ways based on the arguments provided.
o class Car {
String brand;
int year;
// Default constructor
Car() {
brand = "Unknown";
year = 0;
}
// Parameterized constructor with one parameter
Car(String b) {
brand = b;
year = 2022; // default value for year
}
// Parameterized constructor with two parameters
Car(String b, int y) {
brand = b;
year = y;
}
void display() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("Toyota"); // Calls constructor with one parameter
Car car3 = new Car("Honda", 2020); // Calls constructor with two
parameters
car1.display();
car2.display();
car3.display();
}
}
o Output
 Brand: Unknown, Year: 0
Brand: Toyota, Year: 2022
Brand: Honda, Year: 2020
32) Develop a java program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create a subclasses circle and triangle that
extends the Shape class and implement the respective methods to calculate the area and
perimeter of each shape.
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

class Triangle extends Shape {


private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

@Override
double calculateArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
double calculatePerimeter() {
return side1 + side2 + side3;
}
}
public class ShapeDemo {
public static void main(String[] args) {
Circle c = new Circle(5);
System.out.println("Circle area: " + c.calculateArea());
System.out.println("Circle perimeter: " + c.calculatePerimeter());

Triangle t = new Triangle(3, 4, 5);


System.out.println("Triangle area: " + t.calculateArea());
System.out.println("Triangle perimeter: " + t.calculatePerimeter());
}
}
33) Develop a java program to create a class named Shape. Create 3 subclasses namely,
circle, triangle and square, each class has two member functions named draw() and
erase(). Demonstrate polymorphism concept by developing suitable methods , defining
member data and main program.

class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
public void erase() {
System.out.println("Erasing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
@Override
public void erase() {
System.out.println("Erasing a Circle");
}
}
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Triangle");
}

@Override
public void erase() {
System.out.println("Erasing a Triangle");
}
}
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
@Override
public void erase() {
System.out.println("Erasing a Square");
}
}
public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Triangle();
shapes[2] = new Square();
for (Shape shape : shapes) {
shape.draw();
shape.erase();
System.out.println();
}
}
}
34) How argument can be passed in java, explain with a program example.
 Pass by Value: Java uses pass-by-value, meaning that a copy of the argument's value
is passed to the method. Changes to the parameter within the method do not affect
the original argument.
 Pass by Reference (Object Reference): When an object reference is passed, the
reference itself is passed by value. This means the reference points to the original
object, so any changes to the object's properties within the method affect the
original object.
o class PassExample {
// Method to modify a primitive argument
void modifyPrimitive(int num) {
num += 10;
System.out.println("Inside modifyPrimitive: " + num); // Modified value
within method
}
// Method to modify an object argument
void modifyObject(StringBuilder text) {
text.append(" World");
System.out.println("Inside modifyObject: " + text); // Modified text
within method
}
}
public class Main {
public static void main(String[] args) {
PassExample example = new PassExample();
// Passing a primitive type
int number = 5;
System.out.println("Before modifyPrimitive: " + number);
example.modifyPrimitive(number);
System.out.println("After modifyPrimitive: " + number); // Unchanged
because it's pass by value
// Passing an object reference
StringBuilder message = new StringBuilder("Hello");
System.out.println("Before modifyObject: " + message);
example.modifyObject(message);
System.out.println("After modifyObject: " + message); // Changed
because object reference is modified
}
}
35) With an example program, explain how multiple inheritance is supported in Java by
interfaces.
// First interface with a method
interface Printable {
void print();
}
// Second interface with a method
interface Showable {
void show();
}
// Class implementing both interfaces
class Document implements Printable, Showable {
@Override
public void print() {
System.out.println("Printing the document...");
}
@Override
public void show() {
System.out.println("Showing the document...");
}
}
public class Main {
public static void main(String[] args) {
Document doc = new Document();
doc.print(); // Calls Printable's method
doc.show(); // Calls Showable's method
}
}
36) Develop a java program to create an interface resizable with methods resizeWidth(int
width) and resizeHeight(int height) that allow an object to be resized. Create a class
Rectangle that implements the resizable interface and implement the resize methods.

// Define the Resizable interface with methods to resize width and height
interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Rectangle class implementing the Resizable interface


class Rectangle implements Resizable {
private int width;
private int height;

// Constructor to initialize width and height


public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}

// Implement the resizeWidth method


@Override
public void resizeWidth(int newWidth) {
width = newWidth;
System.out.println("Width resized to: " + width);
}

// Implement the resizeHeight method


@Override
public void resizeHeight(int newHeight) {
height = newHeight;
System.out.println("Height resized to: " + height);
}

// Method to display the dimensions of the rectangle


public void displayDimensions() {
System.out.println("Rectangle Dimensions - Width: " + width + ", Height: " + height);
}
}
// Main class to demonstrate the functionality
public class Main {
public static void main(String[] args) {
// Create a Rectangle object
Rectangle rect = new Rectangle(10, 5);

// Display initial dimensions


rect.displayDimensions();

// Resize width and height


rect.resizeWidth(15);
rect.resizeHeight(8);

// Display updated dimensions


rect.displayDimensions();
}
}
37) What is dynamic method dispatch with example in Java?
Dynamic Method Dispatch (also known as runtime polymorphism) is a process in Java where a
method call to an overridden method is resolved at runtime instead of compile-time. This
feature is essential in achieving polymorphism, allowing Java to call the appropriate overridden
method based on the object type that invokes it, even when referenced by a superclass type.
// Superclass with a display method
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog that overrides the sound method


class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

// Subclass Cat that overrides the sound method


class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
// Superclass reference, but objects are of subclass types
Animal myAnimal;

// Assign a Dog object to the Animal reference


myAnimal = new Dog();
myAnimal.sound(); // Calls Dog's sound method

// Assign a Cat object to the Animal reference


myAnimal = new Cat();
myAnimal.sound(); // Calls Cat's sound method
}
}
38) With respect to interface, explain the following with an example for each:a) Default interface
methods b) static methods in interface c) private interface methods.
 Default Interface Methods – Default methods allow an interface to have a concrete
method with an implementation.
interface Vehicle {
void start();

// Default method with implementation


default void honk() {
System.out.println("Honking...");
}
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car is starting.");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start();
car.honk(); // Calls the default method from the Vehicle interface
}
}
 Static Methods in Interface - Static methods in interfaces are similar to static methods
in classes. They belong to the interface itself and can be called using the interface name.
They cannot be overridden by implementing classes.

interface Calculator {
// Static method in interface
static int add(int a, int b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
// Calling the static method using the interface name
int result = Calculator.add(5, 3);
System.out.println("Addition result: " + result);
}
}
 Private Interface Methods - Private methods in interfaces were introduced in Java 9.
They are used to encapsulate code within the interface, making it reusable by other
methods in the interface without exposing it to the implementing classes.

interface Greeting {
default void sayHello() {
System.out.println("Hello!");
printMessage();
}

default void sayGoodbye() {


System.out.println("Goodbye!");
printMessage();
}

// Private method only accessible within the interface


private void printMessage() {
System.out.println("Have a nice day!");
}
}

public class Main {


public static void main(String[] args) {
Greeting greet = new Greeting() {}; // Anonymous class
greet.sayHello();
greet.sayGoodbye();
}
}

You might also like