oop
oop
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
Implement a java program to display the month based on the number Assigned. Use the Scanner
class to take input from the user, specifically a number representing a month(1- 12).the
getMonthName method is defined to map the month number to the corresponding month name
using a switch statement?
String monthName;
switch (monthNumber) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = null;
break;
return monthName;
Noah is developing an application where he needs to initialize some static resources when the
class is loaded. Explain how he can use static blocks for this purpose and provide a code example?
Noah can use a static block in Java to initialize static resources when a class is loaded. A
static block is a block of code that gets executed when the class is first loaded into memory,
before any objects of that class are created or any static methods are called.
static {
}
// Static method to access the config setting
return config;
Tom is building a Car class for a vehicle rental system. He wants to provide different ways to
create a car object: one with only the car model and another with the model and the year. Assign
an 5 objects to one class?
this.model = model;
this.model = model;
this.year = year;
car1.displayCarDetails();
car2.displayCarDetails();
car3.displayCarDetails();
car4.displayCarDetails();
car5.displayCarDetails();
In the serene village of Geometrica, a young architectnamed Lina was working on her latest
design. She needed to calculate the area of several rooms in her newbuilding plans. Lina decided
to use her programming skills to create a simple tool in Java to help her calculatethe area of a
rectangle
import java.util.Scanner;
// Prompt the user for the length and width of the rectangle
System.out.print("Enter the length of the rectangle: ");
System.out.println("The area of the rectangle is: " + area + " square units.");
In the bustling town of Codington, there was a brilliant teacher named Mr. Byte. He was known
for his innovative teaching methods and his ability to make complex concepts simple. One day,
Mr. Byte decided toteach his students how to store and display their grades using Java?
import java.util.Scanner;
grades[i] = scanner.nextInt();
Nick is developing a Student class where he wants to keep the student's details (name and age)
private and provide public methods to access and modify these details?
this.name = name;
this.age = age;
this.name = name;
return age;
this.age = age;
} else {
student1.displayStudentDetails();
student1.setName("Bob");
student1.setAge(22);
student1.displayStudentDetails();
Sarah is implementing a program to calculate the area of a circle. She wants to ensure the value of
PI is constant throughout the program. How she declares the PI variable in her Circle class
// Declare PI as a constant
System.out.println("The area of the circle with radius " + radius + " is: " + area);
Implement a program to display the geometric sequence as given below for a given value n, where
n is the number of elements in the sequence? 1, 2, 4, 8, 16, 32, 64,…. , 1024.
import java.util.Scanner;
int n = scanner.nextInt();
int value = 1;
}
Once upon a time in the kingdom of Mathe magica, there was a legendary number known as the
Armstrong number. This number had a magical property: when you take each digit of the number,
raise it to the power of the number of digits, and sum them up, you would get the original number
itself.The wise wizard Algebrus wanted to create a magical spell to identify these special numbers?
import java.util.Scanner;
if (isArmstrong(number)) {
} else {
int sum = 0;
while (number != 0) {
// Check if the sum of the digits raised to the power of the number of digits equals the original
number
John is working on a library management system. He needs to create a Book class and declare an
object named myBook of that class. Implement this in Java
this.title = title;
this.author = author;
this.publicationYear = publicationYear;
return title;
this.title = title;
}
// Getter and Setter for author
return author;
this.author = author;
return publicationYear;
this.publicationYear = publicationYear;
Book myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);
Mia is working on a Company class to represent employees and departments. She wants to use
static methods to calculate the total number of employees across all departments and a final
variable to represent the company's name. Design the Company class incorporating static
methods, final variables, and access control
this.departmentName = departmentName;
this.numberOfEmployees = numberOfEmployees;
updateTotalEmployees(numberOfEmployees);
totalEmployees += numberOfEmployees;
return totalEmployees;
return departmentName;
return numberOfEmployees;
Once upon a time, in a small village, there was a wiseold man named Mathis. He had a
magical box that could perform calculations. The villagers would come to him with their
arithmetic problems, and he would usethe box to provide solutions. One day, Mathis
decided to teach a young villager named Alex how to implementthis using Java?
import java.util.Scanner;
System.out.println("\nSelect an operation:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
if (num2 != 0) {
} else {
break;
default:
break;
return a + b;
}
// Method to perform subtraction
return a - b;
return a * b;
return a / b;
In the enchanted forest of Alphabetica, a young elf named Elara was known for her
curiosity and love forlanguages. One day, she found an ancient scroll that described how
to identify vowels in any given text. Excited to share her newfound knowledge, Elara
decided to teach her friend, a talking squirrel namedQuill, how to implement this using
Java?
import java.util.Scanner;
identifyVowels(text);
text = text.toLowerCase();
char ch = text.charAt(i);
if (vowels.indexOf(ch) != -1) {
Enna is developing a Counter class where she wants tokeep track of the number of instances
created. She decides to use a static variable for this purpose. Write the Counter class
demonstrating this behaviour?
public class Counter {
// Constructor increments the instance count each time a new object is created
public Counter() {
instanceCount++;
return instanceCount;
Olivia is curious about how Java handles objects. Shewants to understand the entire
lifecycle of an object, from creation to garbage collection. Explain the lifecycle in detail and
provide a Java example demonstrating object creation and garbage collection?
The lifecycle of an object in Java involves several stages, from creation to garbage collection.
Here's a detailed explanation of each stage, along with a Java example demonstrating object
creation and garbage collection.
1. Object Creation:
o
Instantiation: An object is created using the new keyword, which calls a
constructor to initialize the object. Memory is allocated for the object on the
heap.
o Initialization: The constructor initializes the object’s state. Instance variables
are set to default values or to values provided by the constructor.
2. Object Use:
o Access: The object can be accessed and manipulated using references.
Methods can be called, and properties can be modified.
o Reference Counting: An object remains in memory as long as there is at least
one reference pointing to it.
3. Object Finalization (Optional):
o Finalize Method: Before an object is reclaimed by the garbage collector, the
finalize method (if overridden) is called. This method allows the object to
perform cleanup operations before being collected. Note that relying on
finalize is discouraged because it introduces non-deterministic behavior.
4. Garbage Collection:
o Eligibility for Garbage Collection: An object becomes eligible for garbage
collection when no references to it remain. The garbage collector will reclaim
the memory used by such objects.
o Garbage Collection Process: The garbage collector identifies unused objects
and deallocates their memory. This process is automatic but can be triggered
manually using System.gc() (though it is not guaranteed to run).
@Override
try {
System.out.println("Finalizing MyObject...");
} finally {
super.finalize();
// Create an object
obj1 = null;
obj2 = null;
System.gc();
try {
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Program ends.");
In the magical kingdom of Javaland, three young apprentices—Liam, Isla, and Theo—were
learning about the secrets of Java programming from their mentor, Master Byte. One day,
Master Byte decided toteach them about local, instance, and class variables using a special
program designed to track the attributesand activities of their magical pets?
public class MagicalPet {
// Class variable (static variable) to keep track of the total number of pets
private static int totalPets = 0;
// Constructor to initialize the pet's attributes and increment the total pet count
public MagicalPet(String name, String type, int age) {
this.name = name;
this.type = type;
this.age = age;
totalPets++;
}
System.out.println("Implicit Casting:");
System.out.println("\nExplicit Casting:");
System.out.println("\nReal-world Example:");
// Base class
class Animal {
void eat() {
System.out.println("Animal is eating.");
// Subclass of Animal
void bark() {
System.out.println("Dog is barking.");
Tom is building a Car class for a vehicle rental system.He wants to provide different ways to
create a car object: one with only the car model and another with the model and the year.
Write the Car class with overloaded constructors?
public class Car {
private String model;
this.model = model;
this.model = model;
this.year = year;
// Create a Car object using the constructor with only the model
System.out.println("Car 1 Details:");
car1.displayDetails();
// Create a Car object using the constructor with both model and year
System.out.println("\nCar 2 Details:");
car2.displayDetails();
}
Jake is designing a Bank Account class. He wants to ensure that the account balance is only
accessible withinthe class and not modifiable from outside. How can he achieve this using
access control modifiers? Write the Bank Account class?
public class BankAccount {
// Private variable to store the account balance
private double balance;
// Deposit money
account.deposit(500.00);
System.out.println("Balance after deposit: $" + account.getBalance());
// Withdraw money
account.withdraw(200.00);
System.out.println("Balance after withdrawal: $" + account.getBalance());
In the mystical land of Numerica, there was a special class of numbers known as prime
numbers. These numbers were unique because they had only two distinct positive divisors: 1
and themselves. The great sage Arithmo wanted to craft a spell to identify these prime
numbers using the arcane language of Java?
public class PrimeNumberSpell {
return true;
}
castSpell(20, "Ice Blast"); // Calls the method with both int and String parameters
java
Copy code
int[] myArray;
java
Copy code
myArray = new int[10];
java
Copy code
int[] myArray = new int[10];
java
Copy code
myArray[0] = 5;
myArray[1] = 10;
Object: An object is a concrete instance of a class that contains data (fields) and
methods to operate on that data. It represents an individual entity with specific
attributes and behaviors as defined by its class.
final Keyword with Variables: When a variable is declared with the final
keyword, its value cannot be changed once it is initialized. It effectively makes the
variable a constant.
Purpose of Variables: Variables are used to store data that can be manipulated and
accessed by the program. They hold values that are used in computations, conditions,
and other operations.
Encapsulation: Bundling of data and methods that operate on the data into a single
unit (class) and restricting access to some of the object's components.
Inheritance: Mechanism by which one class (subclass) inherits the properties and
behavior of another class (superclass).
Polymorphism: Ability of different classes to be treated as instances of the same
class through a common interface. It allows methods to do different things based on
the object it is acting upon.
Abstraction: Hiding the complex implementation details and showing only the
necessary features of the object.
Type Conversion: Type conversion in Java refers to converting one data type to another.
There are two main types:
java
Copy code
int intValue = 10;
double doubleValue = intValue; // Implicit conversion from int to
double
java
Copy code
double doubleValue = 10.5;
int intValue = (int) doubleValue; // Explicit conversion from double
to int
Benefits:
Steps:
java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
bash
Copy code
java HelloWorld
Syntax Errors: Ensure correct syntax and spelling (e.g., missing semicolons or
braces).
File Not Found: Make sure the file name matches the class name and is in the correct
directory.
Class Not Found: Verify that you are in the correct directory and the class file is
present.
3. Constructor Overloading
Concept: Constructor overloading occurs when a class has multiple constructors with
different parameter lists. It allows for different ways to initialize objects.
Example:
java
Copy code
public class Rectangle {
private int length;
private int width;
Use:
Within Constructors: this refers to the current object and helps to distinguish
between instance variables and parameters with the same name.
java
Copy code
public class Person {
private String name;
Within Methods: this can be used to call other methods in the same class or to refer
to the current object.
java
Copy code
public void display() {
System.out.println(this.name);
}
Importance:
Clarity: Helps avoid ambiguity when variable names are the same.
Object Reference: Allows referring to the current instance's members.
int: Used for whole numbers but can’t handle very large numbers.
double: Used for decimal numbers but can have precision issues with very small or
large numbers.
char: Used for single characters.
boolean: Used for logical values, only true or false.
Limitations:
Fixed Size: Primitive types have a fixed size which limits their range.
No Methods: Primitive types do not have methods or properties.
Scope:
Local Variables: Defined within a method or block, accessible only within that
method or block.
Instance Variables: Defined within a class but outside methods, accessible to all
methods in the class.
Class Variables (Static): Defined with the static keyword, shared among all
instances of the class.
Lifetime:
Local Variables: Exist only during the execution of the method or block.
Instance Variables: Exist as long as the object is in memory.
Class Variables: Exist as long as the class is loaded in the JVM.
Example:
java
Copy code
public class ScopeExample {
private int instanceVar; // Instance variable
Example:
java
Copy code
public class FinalExample {
public static void main(String[] args) {
final int MAX_VALUE = 100;
System.out.println("Max Value: " + MAX_VALUE);
Explanation: The final keyword makes MAX_VALUE a constant. Once assigned, its value
cannot be changed.
Example:
java
Copy code
public class StaticExample {
// Static variable
private static int count = 0;
// Static method
public static void incrementCount() {
count++;
}
Explanation: