0% found this document useful (0 votes)
10 views

oop

The document contains various Java programming examples, including FizzBuzz, month name display, static resource initialization, car object creation, rectangle area calculation, student details management, circle area calculation, geometric sequence generation, Armstrong number checking, book class implementation, company employee tracking, and a magic calculator. Each example demonstrates different programming concepts such as loops, conditionals, classes, methods, and static variables. The examples are designed to help learners understand Java programming through practical applications.

Uploaded by

rahulratna9392
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

oop

The document contains various Java programming examples, including FizzBuzz, month name display, static resource initialization, car object creation, rectangle area calculation, student details management, circle area calculation, geometric sequence generation, Armstrong number checking, book class implementation, company employee tracking, and a magic calculator. Each example demonstrates different programming concepts such as loops, conditionals, classes, methods, and static variables. The examples are designed to help learners understand Java programming through practical applications.

Uploaded by

rahulratna9392
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Implement a program that prints the numbers from 1 to 100.

But for multiples of three, print


“Fizz” instead of the number, and for the multiples of five, print “Buzz”. For numbers that are
multiples of both three and five, print “FizzBuzz”?

public class FizzBuzz {

public static void main(String[] args) {

for (int i = 1; i <= 100; i++) {

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?

// Method to return the month name based on the month number

public static String getMonthName(int monthNumber) {

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.

When to Use Static Blocks:

 Loading Configuration Files: If the application needs to load configuration settings


from a file when the class is loaded.
 Initializing Static Variables: When certain static variables require complex
initialization that can't be done in a single statement.
 Database Connections: For establishing connections to databases or initializing
connection pools.

public class ResourceInitializer {

// Static variable to hold a configuration setting

private static String config;

// Static block to initialize the static variable

static {

System.out.println("Loading static resources...");

// Simulate loading configuration from a file or another resource

config = "Loaded Configuration Settings";

System.out.println("Static resources loaded.");

}
// Static method to access the config setting

public static String getConfig() {

return config;

public static void main(String[] args) {

// Accessing the static config variable to show that it's initialized

System.out.println("Config: " + ResourceInitializer.getConfig());

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?

public class Car {

private String model;

private int year;

// Constructor 1: Only model

public Car(String model) {

this.model = model;

this.year = 0; // default value if the year is not provided

// Constructor 2: Model and year

public Car(String model, int year) {

this.model = model;

this.year = year;

// Method to display car details


public void displayCarDetails() {

System.out.println("Model: " + model + ", Year: " + (year == 0 ? "Unknown" : year));

public static void main(String[] args) {

// Creating car objects using different constructors

Car car1 = new Car("Toyota Corolla");

Car car2 = new Car("Honda Civic", 2020);

Car car3 = new Car("Ford Mustang", 2018);

Car car4 = new Car("Chevrolet Camaro");

Car car5 = new Car("Tesla Model S", 2021);

// Displaying the details of each car

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;

public class RectangleAreaCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user for the length and width of the rectangle
System.out.print("Enter the length of the rectangle: ");

double length = scanner.nextDouble();

System.out.print("Enter the width of the rectangle: ");

double width = scanner.nextDouble();

// Calculate the area of the rectangle

double area = calculateArea(length, width);

// Display the area

System.out.println("The area of the rectangle is: " + area + " square units.");

// Method to calculate the area of a rectangle

public static double calculateArea(double length, double width) {

return length * width;

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;

public class GradesManager {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the number of students

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

int numberOfStudents = scanner.nextInt();


// Create an array to store the grades

int[] grades = new int[numberOfStudents];

// Input grades for each student

for (int i = 0; i < numberOfStudents; i++) {

System.out.print("Enter the grade for student " + (i + 1) + ": ");

grades[i] = scanner.nextInt();

// Display the grades

System.out.println("\nGrades of the students:");

for (int i = 0; i < numberOfStudents; i++) {

System.out.println("Student " + (i + 1) + ": " + grades[i]);

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?

public class Student {

// Private fields for student details

private String name;

private int age;

// Constructor to initialize the student details

public Student(String name, int age) {

this.name = name;

this.age = age;

// Getter method for name

public String getName() {


return name;

// Setter method for name

public void setName(String name) {

this.name = name;

// Getter method for age

public int getAge() {

return age;

// Setter method for age

public void setAge(int age) {

if (age > 0) { // Basic validation to ensure age is positive

this.age = age;

} else {

System.out.println("Please enter a valid age.");

// Method to display student details

public void displayStudentDetails() {

System.out.println("Name: " + name + ", Age: " + age);

public static void main(String[] args) {

// Creating a Student object

Student student1 = new Student("Alice", 20);


// Displaying initial details

student1.displayStudentDetails();

// Modifying the student's details using setter methods

student1.setName("Bob");

student1.setAge(22);

// Displaying updated details

student1.displayStudentDetails();

// Attempting to set an invalid age

student1.setAge(-5); // Should display an error message

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

public class Circle {

// Declare PI as a constant

public static final double PI = 3.14159;

// Method to calculate the area of a circle

public double calculateArea(double radius) {

return PI * radius * radius;

public static void main(String[] args) {

// Create a Circle object

Circle circle = new Circle();

// Example: Calculate the area of a circle with radius 5


double radius = 5.0;

double area = circle.calculateArea(radius);

// Display the area

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;

public class GeometricSequence {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the number of elements in the sequence

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

int n = scanner.nextInt();

// Start with the first element in the sequence

int value = 1;

// Loop to generate and display the sequence

for (int i = 1; i <= n; i++) {

System.out.print(value + " ");

value *= 2; // Multiply by 2 to get the next element

}
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;

public class ArmstrongNumberChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number: ");

int number = scanner.nextInt();

// Check if the number is an Armstrong number

if (isArmstrong(number)) {

System.out.println(number + " is an Armstrong number.");

} else {

System.out.println(number + " is not an Armstrong number.");

// Method to check if a number is an Armstrong number

public static boolean isArmstrong(int number) {

int originalNumber = number;

int sum = 0;

int numberOfDigits = String.valueOf(number).length();

while (number != 0) {

int digit = number % 10;

sum += Math.pow(digit, numberOfDigits);


number /= 10;

// Check if the sum of the digits raised to the power of the number of digits equals the original
number

return sum == originalNumber;

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

// Define the Book class

public class Book {

// Private attributes for the Book class

private String title;

private String author;

private int publicationYear;

// Constructor to initialize the Book object

public Book(String title, String author, int publicationYear) {

this.title = title;

this.author = author;

this.publicationYear = publicationYear;

// Getter and Setter for title

public String getTitle() {

return title;

public void setTitle(String title) {

this.title = title;

}
// Getter and Setter for author

public String getAuthor() {

return author;

public void setAuthor(String author) {

this.author = author;

// Getter and Setter for publicationYear

public int getPublicationYear() {

return publicationYear;

public void setPublicationYear(int publicationYear) {

this.publicationYear = publicationYear;

// Method to display book details

public void displayBookDetails() {

System.out.println("Title: " + title);

System.out.println("Author: " + author);

System.out.println("Publication Year: " + publicationYear);

public static void main(String[] args) {

// Create a Book object named myBook

Book myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925);

// Display the details of myBook


myBook.displayBookDetails();

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

public class Company {

// Final variable for the company name

public static final String COMPANY_NAME = "Tech Innovators Inc.";

// Static variable to keep track of the total number of employees

private static int totalEmployees = 0;

// Private attributes for the department

private String departmentName;

private int numberOfEmployees;

// Constructor to initialize a department with its number of employees

public Company(String departmentName, int numberOfEmployees) {

this.departmentName = departmentName;

this.numberOfEmployees = numberOfEmployees;

// Update the total number of employees when a new department is added

updateTotalEmployees(numberOfEmployees);

// Static method to update the total number of employees

private static void updateTotalEmployees(int numberOfEmployees) {

totalEmployees += numberOfEmployees;

// Static method to get the total number of employees


public static int getTotalEmployees() {

return totalEmployees;

// Getter for department name

public String getDepartmentName() {

return departmentName;

// Getter for number of employees in the department

public int getNumberOfEmployees() {

return numberOfEmployees;

// Main method to test the Company class

public static void main(String[] args) {

// Creating departments with their employee counts

Company dept1 = new Company("Engineering", 50);

Company dept2 = new Company("Marketing", 30);

Company dept3 = new Company("Sales", 20);

// Display company name

System.out.println("Company Name: " + COMPANY_NAME);

// Display total number of employees across all departments

System.out.println("Total Number of Employees: " + Company.getTotalEmployees());

// Display details of each department

System.out.println(dept1.getDepartmentName() + " Department Employees: " +


dept1.getNumberOfEmployees());

System.out.println(dept2.getDepartmentName() + " Department Employees: " +


dept2.getNumberOfEmployees());
System.out.println(dept3.getDepartmentName() + " Department Employees: " +
dept3.getNumberOfEmployees());

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;

public class MagicCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter two numbers

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

double num1 = scanner.nextDouble();

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

double num2 = scanner.nextDouble();

// Display the menu of operations

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");

// Prompt the user to select an operation


System.out.print("Enter the number of the operation you want to perform (1-4): ");

int choice = scanner.nextInt();

// Perform the selected operation

switch (choice) {

case 1:

System.out.println("Result of addition: " + add(num1, num2));

break;

case 2:

System.out.println("Result of subtraction: " + subtract(num1, num2));

break;

case 3:

System.out.println("Result of multiplication: " + multiply(num1, num2));

break;

case 4:

if (num2 != 0) {

System.out.println("Result of division: " + divide(num1, num2));

} else {

System.out.println("Error: Division by zero is not allowed.");

break;

default:

System.out.println("Invalid choice. Please select a valid operation.");

break;

// Method to perform addition

public static double add(double a, double b) {

return a + b;

}
// Method to perform subtraction

public static double subtract(double a, double b) {

return a - b;

// Method to perform multiplication

public static double multiply(double a, double b) {

return a * b;

// Method to perform division

public static double divide(double a, double 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;

public class VowelIdentifier {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a text

System.out.print("Enter a text: ");

String text = scanner.nextLine();


// Call the method to identify and print vowels in the text

identifyVowels(text);

// Method to identify and print vowels in the given text

public static void identifyVowels(String text) {

// Convert the text to lowercase to handle case insensitivity

text = text.toLowerCase();

// Vowels to look for

String vowels = "aeiou";

// Iterate through each character in the text

System.out.print("Vowels in the text: ");

for (int i = 0; i < text.length(); i++) {

char ch = text.charAt(i);

// Check if the character is a vowel

if (vowels.indexOf(ch) != -1) {

System.out.print(ch + " ");

System.out.println(); // Move to the next line after printing vowels

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 {

// Static variable to keep track of the number of instances


private static int instanceCount = 0;

// Constructor increments the instance count each time a new object is created

public Counter() {

instanceCount++;

// Static method to get the current count of instances

public static int getInstanceCount() {

return instanceCount;

public static void main(String[] args) {

// Create instances of the Counter class

Counter c1 = new Counter();

Counter c2 = new Counter();

Counter c3 = new Counter();

// Display the number of instances created

System.out.println("Number of instances created: " + Counter.getInstanceCount());

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.

Lifecycle of an Object in Java

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).

public class ObjectLifecycle {

// Class with a finalizer (not recommended for real use)

static class MyObject {

@Override

protected void finalize() throws Throwable {

try {

System.out.println("Finalizing MyObject...");

} finally {

super.finalize();

public static void main(String[] args) {

// Create an object

MyObject obj1 = new MyObject();


System.out.println("Object obj1 created.");

// Create another object

MyObject obj2 = new MyObject();

System.out.println("Object obj2 created.");

// Nullify references to objects

obj1 = null;

obj2 = null;

System.out.println("References to obj1 and obj2 set to null.");

// Request garbage collection

System.gc();

System.out.println("Garbage collection requested.");

// Wait for a while to allow garbage collection to occur

try {

Thread.sleep(2000); // Sleep for 2 seconds

} 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;

// Instance variables to store pet attributes


private String name;
private String type;
private int age;

// 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++;
}

// Instance method to display pet details


public void displayPetDetails() {
// Local variables for the method
String details = "Pet Name: " + name + "\nPet Type: " + type + "\nPet Age: " + age;
System.out.println(details);
}

// Static method to display the total number of pets


public static void displayTotalPets() {
System.out.println("Total number of pets: " + totalPets);
}

public static void main(String[] args) {


// Create magical pet objects
MagicalPet pet1 = new MagicalPet("Fluffy", "Unicorn", 3);
MagicalPet pet2 = new MagicalPet("Sparkle", "Dragon", 5);

// Display details of each pet


pet1.displayPetDetails();
pet2.displayPetDetails();

// Display the total number of pets


MagicalPet.displayTotalPets();
}
}
In the kingdom of Java land, a young programmer named Aria was learning the art of type
casting from the wise coder, Master Byte. Master Byte decided to teach Aria about implicit
and explicit type casting usingreal-world examples. Implement by using java?
public class TypeCastingDemo {

public static void main(String[] args) {

// Implicit Type Casting (Widening Conversion)

int intValue = 100;

double doubleValue = intValue; // Implicit casting from int to double

System.out.println("Implicit Casting:");

System.out.println("Integer value: " + intValue);

System.out.println("Double value after implicit casting: " + doubleValue);

// Explicit Type Casting (Narrowing Conversion)

double anotherDoubleValue = 99.99;

int anotherIntValue = (int) anotherDoubleValue; // Explicit casting from double to int

System.out.println("\nExplicit Casting:");

System.out.println("Double value: " + anotherDoubleValue);

System.out.println("Integer value after explicit casting: " + anotherIntValue);


// Real-world example: Casting between different types of objects

System.out.println("\nReal-world Example:");

// Create a base class object

Animal myAnimal = new Dog();

// Downcasting to access subclass-specific method

if (myAnimal instanceof Dog) {

Dog myDog = (Dog) myAnimal;

myDog.bark(); // Calling a method specific to Dog

// Base class

class Animal {

void eat() {

System.out.println("Animal is eating.");

// Subclass of Animal

class Dog extends 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;

private int year;

// Constructor with only the model parameter

public Car(String model) {

this.model = model;

this.year = 2024; // Default year

// Constructor with both model and year parameters

public Car(String model, int year) {

this.model = model;

this.year = year;

// Method to display car details

public void displayDetails() {

System.out.println("Car Model: " + model);

System.out.println("Car Year: " + year);

public static void main(String[] args) {

// Create a Car object using the constructor with only the model

Car car1 = new Car("Toyota Corolla");

System.out.println("Car 1 Details:");

car1.displayDetails();

// Create a Car object using the constructor with both model and year

Car car2 = new Car("Honda Civic", 2022);

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;

// Constructor to initialize the account with a starting balance


public BankAccount(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
System.out.println("Initial balance cannot be negative.");
this.balance = 0;
}
}

// Public method to deposit money into the account


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Deposit amount must be positive.");
}
}

// Public method to withdraw money from the account


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient funds or invalid withdrawal amount.");
}
}

// Public method to get the current balance (read-only access)


public double getBalance() {
return balance;
}

public static void main(String[] args) {


// Create a BankAccount object with an initial balance
BankAccount account = new BankAccount(1000.00);

// Display initial balance


System.out.println("Initial Balance: $" + account.getBalance());

// 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());

// Attempt to withdraw more than the balance


account.withdraw(1500.00);
// Attempt to deposit a negative amount
account.deposit(-100.00);
}
}

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 {

// Method to check if a number is prime


public static boolean isPrime(int number) {
// Numbers less than 2 are not prime
if (number <= 1) {
return false;
}
// Check for factors from 2 to the square root of the number
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}

public static void main(String[] args) {


// Test numbers
int[] numbersToTest = {2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 17, 19, 23, 25, 29};
// Display results for each number
System.out.println("Prime numbers:");
for (int num : numbersToTest) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
}
In the enchanted kingdom of Symmetria, there was a curious phenomenon known as
palindromes. These were words or phrases that read the same backward as forward. The
wise sorceress Palindrina decided to craft a magical incantation in the language of Java to
detect these symmetrical marvels?
public class PalindromeDetector {

// Method to check if a string is a palindrome


public static boolean isPalindrome(String str) {
// Remove non-alphanumeric characters and convert to lowercase
String cleanedStr = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();

// Initialize pointers for start and end of the string


int start = 0;
int end = cleanedStr.length() - 1;

// Check for palindrome by comparing characters from both ends


while (start < end) {
if (cleanedStr.charAt(start) != cleanedStr.charAt(end)) {
return false;
}
start++;
end--;
}

return true;
}

public static void main(String[] args) {


// Test phrases
String[] phrasesToTest = {
"A man, a plan, a canal, Panama!",
"Madam, in Eden I'm Adam",
"Hello, World!",
"Racecar",
"No lemon, no melon"
};

// Display results for each phrase


System.out.println("Palindrome phrases:");
for (String phrase : phrasesToTest) {
if (isPalindrome(phrase)) {
System.out.println("\"" + phrase + "\"");
}
}
}
}
Emily is developing a game and wants to create a Player class where each player has a name.
She wants to set the player's name when creating a new player object. How can she achieve
this using a constructor?
public class Player {
// Instance variable to store the player's name
private String name;

// Constructor to initialize the player's name


public Player(String name) {
this.name = name;
}

// Method to get the player's name


public String getName() {
return name;
}

// Method to set the player's name


public void setName(String name) {
this.name = name;
}

// Main method to demonstrate the usage of Player class


public static void main(String[] args) {
// Create new Player objects with names
Player player1 = new Player("Alice");
Player player2 = new Player("Bob");

// Display player names


System.out.println("Player 1: " + player1.getName());
System.out.println("Player 2: " + player2.getName());

// Change the name of player1


player1.setName("Charlie");
System.out.println("Updated Player 1: " + player1.getName());
}
}
Architect Polymorpha could design versatile methods that could handle various types of
inputs, making her spells more flexible and powerful. The inhabitants of Codoria marveled
at her ingenuity and celebrated the elegance of method overloading in their enchanted
land?
public class PolymorphSpell {

// Method to handle integer input

public static void castSpell(int power) {

System.out.println("Casting spell with power: " + power);

// Method to handle double input

public static void castSpell(double power) {

System.out.println("Casting spell with power (double): " + power);

// Method to handle string input

public static void castSpell(String spellName) {

System.out.println("Casting spell: " + spellName);

// Method to handle integer and string inputs

public static void castSpell(int power, String spellName) {

System.out.println("Casting spell '" + spellName + "' with power: " + power);

// Main method to demonstrate method overloading

public static void main(String[] args) {


// Call overloaded methods with different parameters

castSpell(10); // Calls the method with int parameter

castSpell(15.5); // Calls the method with double parameter

castSpell("Fireball"); // Calls the method with String parameter

castSpell(20, "Ice Blast"); // Calls the method with both int and String parameters

1. Feature Making Java an Internet-Enabled Language:

 Java's Platform Independence: Java is designed to be platform-independent through


its "write once, run anywhere" capability. This is achieved by compiling Java
programs into bytecode, which can be executed on any device that has a Java Virtual
Machine (JVM). This feature is crucial for developing internet-based applications as it
ensures compatibility across different operating systems and hardware.

2. Concept of Bytecode in Java:

 Bytecode: Bytecode is an intermediate code generated by the Java compiler from


Java source code. It is platform-independent and can be executed by the Java Virtual
Machine (JVM). Bytecode is not machine-specific, allowing Java programs to be run
on any device with a JVM, thus achieving portability.

3. Two Primitive Data Types in Java:

 int: Represents a 32-bit integer.


 boolean: Represents a boolean value (true or false).

4. Define a Class and an Object:

 Class: A class is a blueprint or template in Java used to create objects. It defines


properties (fields) and methods that the objects created from the class will have.
 Object: An object is an instance of a class. It represents a specific entity with its own
state and behavior as defined by the class.

5. Define a Constructor in a Class:

 Constructor: A constructor is a special method in a class that is invoked when an


object is created. It initializes the object's state. Constructors have the same name as
the class and do not have a return type.

6. Access Control Modifiers in a Class:

 private: Accessible only within the class.


 default (no modifier): Accessible within the same package.
 protected: Accessible within the same package and by subclasses.
 public: Accessible from any other class.

7. Scope of a Local Variable in Java:

 Scope of a Local Variable: A local variable is defined within a method or a block


and is only accessible within that method or block. It is not visible outside its defining
scope.

8. Steps to Declare a Single-Dimensional Array in Java:

1. Declare the Array:

java
Copy code
int[] myArray;

2. Initialize the Array:

java
Copy code
myArray = new int[10];

Alternatively, you can combine declaration and initialization:

java
Copy code
int[] myArray = new int[10];

3. Assign Values (Optional):

java
Copy code
myArray[0] = 5;
myArray[1] = 10;

9. Function of the if Statement in Java:

 if Statement: The if statement evaluates a boolean expression. If the expression


evaluates to true, the block of code inside the if statement is executed. If it evaluates
to false, the block of code is skipped.

10. Describe an Object in Java:

 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.

11. Purpose of a Constructor:


 Purpose of a Constructor: A constructor initializes newly created objects. It sets the
initial values for the object’s attributes and can perform any setup required before the
object is used.

12. Use of the final Keyword with Variables:

 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.

13. Purpose of Variables in Java:

 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.

14. Two Arithmetic Operators in Java:

 + (Addition): Adds two operands.


 - (Subtraction): Subtracts the second operand from the first.

15. Principles of OOP (Object-Oriented Programming) Concept:

 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.

16. Define Method Overloading:

 Method Overloading: Method overloading occurs when multiple methods in the


same class have the same name but different parameter lists (different types or
numbers of parameters). It allows a class to have more than one method with the same
name, enhancing flexibility.

17. Benefits of Garbage Collection in a Programming Language:

 Automatic Memory Management: Garbage collection automatically reclaims


memory used by objects that are no longer reachable, reducing the risk of memory
leaks and improving program stability.
 Simplified Code: Developers do not need to manually manage memory, leading to
simpler and more maintainable code.

18. Define static Keyword:


 static Keyword: The static keyword is used to declare class-level variables and
methods. These members belong to the class itself rather than any particular instance.
They can be accessed directly using the class name and do not require an instance of
the class to be used.

. Type Conversion and Casting in Java

Type Conversion: Type conversion in Java refers to converting one data type to another.
There are two main types:

 Implicit Conversion (Widening): Automatically performed by Java when converting


from a smaller data type to a larger one (e.g., int to double).

java
Copy code
int intValue = 10;
double doubleValue = intValue; // Implicit conversion from int to
double

 Explicit Conversion (Narrowing): Requires casting when converting from a larger


data type to a smaller one (e.g., double to int).

java
Copy code
double doubleValue = 10.5;
int intValue = (int) doubleValue; // Explicit conversion from double
to int

Benefits:

 Flexibility: Allows for operations on different types of data.


 Resource Efficiency: Helps in optimizing memory usage by converting to smaller
data types when necessary.

2. Steps to Compile and Run a Simple Java Program

Steps:

1. Write the Program:


o Create a Java file (e.g., HelloWorld.java) with the following code:

java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

2. Compile the Program:


o Open a terminal or command prompt and navigate to the directory containing
HelloWorld.java.
o Compile the program using javac:
bash
Copy code
javac HelloWorld.java

oThis generates a HelloWorld.class file containing bytecode.


3. Run the Program:
o Execute the compiled bytecode using the java command:

bash
Copy code
java HelloWorld

o Output: Hello, World!

Common Errors and Solutions:

 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;

// Constructor with no arguments


public Rectangle() {
this.length = 1;
this.width = 1;
}

// Constructor with one argument


public Rectangle(int length) {
this.length = length;
this.width = 1;
}

// Constructor with two arguments


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

// Method to display dimensions


public void display() {
System.out.println("Length: " + length + ", Width: " + width);
}

public static void main(String[] args) {


Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5);
Rectangle r3 = new Rectangle(5, 10);

r1.display(); // Length: 1, Width: 1


r2.display(); // Length: 5, Width: 1
r3.display(); // Length: 5, Width: 10
}
}

4. Use and Importance of this Keyword

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;

public Person(String name) {


this.name = name; // 'this.name' refers to the instance
variable
}
}

 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.

5. Data Types in Java

Primitive Data Types:

 int: 32-bit integer.


 double: 64-bit floating-point number.
 char: 16-bit Unicode character.
 boolean: Represents true or false.
Uses and Limitations:

 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.

6. Scope and Lifetime of Variables

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

public void method() {


int localVar = 5; // Local variable
if (localVar > 0) {
int blockVar = 10; // Block variable
System.out.println(localVar);
}
// System.out.println(blockVar); // Error: blockVar not accessible
here
}
}

7. final Keyword with Variables

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);

// MAX_VALUE = 200; // Error: Cannot assign a value to final


variable MAX_VALUE
}
}

Explanation: The final keyword makes MAX_VALUE a constant. Once assigned, its value
cannot be changed.

8. Static Methods and Variables

Static Methods and Variables:

 Static Variables: Shared among all instances of a class.


 Static Methods: Can be called without creating an instance of the class. They can
only access static variables and methods.

Example:

java
Copy code
public class StaticExample {
// Static variable
private static int count = 0;

// Static method
public static void incrementCount() {
count++;
}

public static void main(String[] args) {


// Access static method without creating an instance
StaticExample.incrementCount();
System.out.println("Count: " + StaticExample.count);
}
}

Explanation:

 count is a static variable shared across all instances.


 incrementCount is a static method that modifies the static variable.

You might also like