Java QB M1 M2
Java QB M1 M2
Java QB M1 M2
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
}
}
// 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
}
}
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);
}
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
17) Write a Java program to find the biggest among n numbers using the ternary operator.
import java.util.Scanner;
// 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:
B) Cellphone
Attributes:
String brand
String model
String operatingSystem
int batteryLife
double screenSize
Behaviors:
Attributes:
String color
String size
String fabric
String style
double price
Behaviors:
D) Course
Attributes:
String courseName
String courseCode
int credits
String instructor
List<String> enrolledStudents
Behaviors:
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;
}
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");
}
}
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;
}
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
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
@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());
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);
}
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();
}