OBJECT ORIENTED PROGRAMMING LAB
[Link] program to display "Hello World" and display
the size of all the data types.
public class PrimitiveDataTypes {
public static void main(String[] args) {
// Display "Hello World"
[Link]("Hello World!");
// Display the size of all primitive data types
[Link]("Size of byte: " + [Link] + " bits");
[Link]("Size of short: " + [Link] + " bits");
[Link]("Size of int: " + [Link] + " bits");
[Link]("Size of long: " + [Link] + " bits");
[Link]("Size of float: " + [Link] + " bits");
[Link]("Size of double: " + [Link] + " bits");
[Link]("Size of char: " + [Link] + " bits");
[Link]("Size of boolean: Typically 1 bit
(implementation-dependent)");
}
}
Output:
Hello World!
Size of byte: 8 bits
Size of short: 16 bits
Size of int: 32 bits
Size of long: 64 bits
Size of float: 32 bits
Size of double: 64 bits
Size of char: 16 bits
Size of boolean: Typically 1 bit (implementation-dependent)
2. Java program to implement the usage of static, local and
global variables.
public class Program2 {
// Static variable (global)
static int staticVariable = 10;
// Instance variable (global)
int instanceVariable = 20;
public void displayVariables() {
// Local variable
int localVariable = 30;
// Displaying the values of all variables
[Link]("Static Variable: " + staticVariable);
[Link]("Instance Variable: " + instanceVariable);
[Link]("Local Variable: " + localVariable);
}
public static void main(String[] args) {
// Creating an object to access instance variable
Program2 example = new Program2();
// Accessing the method to display variables
[Link]();
// Accessing the static variable directly using class name
[Link]("Accessing Static Variable from main: " +
[Link]);
}
}
Output:
Static Variable: 10
Instance Variable: 20
Local Variable: 30
Accessing Static Variable from main: 10
3. Java program to implement string operations string length,
string concatenate, substring
public class StringOperations {
public static void main(String[] args) {
// Initialize strings
String str1 = "Hello";
String str2 = "World";
// 1. String Length
int lengthOfStr1 = [Link]();
[Link]("Length of '" + str1 + "': " + lengthOfStr1);
// 2. String Concatenation
String concatenatedString = [Link](" ").concat(str2);
[Link]("Concatenated String: " +
concatenatedString);
// 3. Substring
String substring = [Link](0, 5); //
Extracting "Hello"
[Link]("Substring: " + substring);
}
}
Output:
Length of 'Hello': 5
Concatenated String: Hello World
Substring: Hello
4. Java program to find the maximum of three numbers.
import [Link]; // Import Scanner class
public class MaxNumberFinder {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter three numbers
[Link]("Enter the first number: ");
int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
[Link]("Enter the third number: ");
int num3 = [Link]();
// Initialize a variable to hold the maximum value
int max;
// Compare the numbers to find the maximum
if (num1 >= num2 && num1 >= num3) {
max = num1; // num1 is greater than or equal to both
num2 and num3
} else if (num2 >= num1 && num2 >= num3) {
max = num2; // num2 is greater than or equal to both
num1 and num3
} else {
max = num3; // If neither of the above, then num3 is
the largest
}
// Display the maximum number
[Link]("The maximum number is: " + max);
// Close the scanner
[Link]();
}
}
Output:
int max = [Link](num1, [Link](num2, num3));
5. Java program to check whether the number is odd or even.
import [Link]; // Import Scanner class
public class Program5 {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a number
[Link]("Enter a number: ");
int num = [Link]();
// Check if the number is even or odd using the
modulus operator
if (num % 2 == 0) {
[Link](num + " is even");
} else {
[Link](num + " is odd");
}
// Close the scanner
[Link]();
}
}
Output:
[Link] a number: 8
8 is even
[Link] a number: 7
7 is odd
6. Java program to implement default and parameterized
constructors.
class MyClass {
// Instance variables
int number;
String text;
// Default constructor
public MyClass() {
number = 0; // Initialize number to 0
text = "Default Text"; // Initialize text to a default string
}
// Parameterized constructor
public MyClass(int num, String str) {
number = num; // Assign the passed value to number
text = str; // Assign the passed value to text
}
// Method to display values
public void display() {
[Link]("Number: " + number);
[Link]("Text: " + text);
}
}
class Program6 { // Class name corrected
public static void main(String[] args) {
// Creating an object using the default constructor
MyClass obj1 = new MyClass();
[Link]("Using Default Constructor:");
[Link](); // Display default values
// Creating an object using the parameterized constructor
MyClass obj2 = new MyClass(42, "Parameterized Text");
[Link]("\nUsing Parameterized Constructor:");
[Link](); // Display assigned values
}
}
Output:
Using Default Constructor:
Number: 0
Text: Default Text
Using Parameterized Constructor:
Number: 42
Text: Parameterized Text
7. Java program to implement an array of objects.
class Student {
// Instance variables
int id;
String name;
// Constructor to initialize the student object
public Student(int id, String name) {
[Link] = id;
[Link] = name;
}
// Method to display student details
public void display() {
[Link]("ID: " + id + ", Name: " + name);
}
}
class Program7 { // Corrected class name
public static void main(String[] args) {
// Creating an array of Student objects
Student[] students = new Student[3]; // Array to hold 3 Student
objects
// Initializing the array with Student objects
students[0] = new Student(1, "Alice");
students[1] = new Student(2, "Bob");
students[2] = new Student(3, "Charlie");
// Displaying the details of each student
for (Student student : students) {
[Link]();
}
}
}
Output:
ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie
8. Java program to implement Single Inheritance.
class Animal {
// Method in the parent class
public void eat() {
[Link]("Animal is eating");
}
}
// Child class that extends the Animal class
class Dog extends Animal {
// Method in the child class
public void bark() {
[Link]("Dog is barking");
}
}
// Main class to test the inheritance
class program8 {
public static void main(String[] args) {
// Create an object of the Dog class
Dog myDog = new Dog();
// Call the inherited method from Animal class
[Link](); // Output: Animal is eating
// Call the method from Dog class
[Link](); // Output: Dog is barking
}
}
Output:
Animal is eating
Dog is barking
[Link] program to implement Multiple Inheritance using
Interface.
// Defining the Walkable interface
interface Walkable {
void walk(); // Abstract method
}
// Defining the Swimmable interface
interface Swimmable {
void swim(); // Abstract method
}
// Implementing both interfaces in a single class
class Duck implements Walkable, Swimmable {
// Implementing the walk method from Walkable interface
public void walk() {
[Link]("Duck is walking.");
}
// Implementing the swim method from Swimmable interface
public void swim() {
[Link]("Duck is swimming.");
}
}
// Main class to test the implementation
public class program9 {
public static void main(String[] args) {
// Create an object of Duck class
Duck myDuck = new Duck();
// Call the methods from both interfaces
[Link](); // Output: Duck is walking.
[Link](); // Output: Duck is swimming.
}
}
Output:
Duck is walking.
Duck is swimming.
10. Java program to implement the Life cycle of the applet.
import [Link].*;
import [Link].*;
public class Program10 extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link]("Hello, World!", 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
Program10 panel = new Program10();
[Link](panel);
[Link](400, 400);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output:
appletviewer [Link]
[Link] program to demonstrate a division by zero exception.
class Program11 {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0; // Setting denominator to zero
try {
if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be
zero.");
}
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Execution completed.");
}
}
}
Output:
Error: / by zero
Cannot divide a number by zero.
12. Java program to add two integers and two float numbers.
When no arguments are supplied give a default value to calculate
the sum. Use method overloading.
class program12 {
// Method to add two integers with default values
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add two float numbers with default
values
public float add(float a, float b) {
return a + b;
}
// Method to add two integers using default values
public int add() {
return add(5, 10); // Default values for integers
}
// Overloaded method to add two float numbers using default
values
public float add(float a) {
return add(a, 5.0f); // Default value for the second float
number
}
public static void main(String[] args) {
program12 calculator = new program12();
// Adding two integers without default values
int intSum = [Link](3, 7);
[Link]("Sum of integers: " + intSum); // Output: 10
// Adding two float numbers without default values
float floatSum = [Link](3.5f, 2.5f);
[Link]("Sum of floats: " + floatSum); // Output: 6.0
// Adding two integers with default values
int defaultIntSum = [Link]();
[Link]("Sum of integers with default values: " +
defaultIntSum); // Output: 15
// Adding two float numbers with one default value
float defaultFloatSum = [Link](4.5f);
[Link]("Sum of floats with one default value: " +
defaultFloatSum); // Output: 9.5
}
}
Output:
Sum of integers: 10
Sum of floats: 6.0
Sum of integers with default values: 15
Sum of floats with one default value: 9.5
13. Java program that demonstrates run-time polymorphism.
// Parent class
class Animal {
public void sound() {
[Link]("Animal makes a sound");
}
}
// Child classes with method overriding
class Dog extends Animal {
@Override
public void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
public void sound() {
[Link]("Cat meows");
}
}
class Cow extends Animal {
@Override
public void sound() {
[Link]("Cow moos");
}
}
// Main class demonstrating polymorphism with an array
class Program13 {
public static void main(String[] args) {
// Creating an array of Animal references
Animal[] animals = {new Dog(), new Cat(), new Cow()};
// Looping through and calling overridden methods
for (Animal animal : animals) {
[Link]();
}
}
}
Output:
Dog barks
Cat meows
14. Java program to catch negative array size Exception. This
exception is caused when the array is initialized to negative
values.
import [Link];
class Program14 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the array size: ");
int size = [Link]();
if (size < 0) {
[Link]("Error: Array size cannot be negative.");
} else {
int[] array = new int[size];
[Link]("Array of size " + size + " created
successfully.");
}
[Link]("Continuing execution...");
[Link]();
}
}
Output:
Error: Attempted to create an array with a negative size.
[Link]: -5
at [Link]([Link]) // Stack trace may vary
Continuing execution...
15. Java program to handle null pointer exception and use the
"finally" method to display a message to the user.
import [Link];
class Program15 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link](); // Read user input
if (str == null || [Link]()) {
[Link]("Error: String is null or empty.");
} else {
[Link]("Length of the string: " + [Link]());
}
[Link]("Execution completed. Please check your
variables.");
[Link]();
}
}
Output:
Error: A NullPointerException has been caught.
You cannot access methods or properties of a null object.
Execution completed. Please check your variables.
16. Java program to import user-defined packages.
package mypackage;
public class Greeting {
public void displayMessage() {
[Link]("Hello from the Greeting class!");
}
}
Output:
Hello from the Greeting class!
17. Java program to check whether a number is palindrome or
not.
import [Link];
class Program17 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt for number input
[Link]("Enter a number: ");
int originalNum = [Link]();
// Reject negative numbers
if (originalNum < 0) {
[Link](originalNum + " is not a palindrome
(negative numbers are not considered).");
} else {
int num = originalNum, reversedNum = 0;
// Reverse the number
while (num != 0) {
int remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
// Check for palindrome
if (originalNum == reversedNum) {
[Link](originalNum + " is a palindrome.");
} else {
[Link](originalNum + " is not a palindrome.");
}
}
// Prompt for string input
[Link]("\nEnter a word or phrase: ");
[Link](); // Consume newline
String str = [Link]().replaceAll("[^a-zA-Z0-9]",
"").toLowerCase(); // Normalize input
// Check if the string is a palindrome
String reversedStr = new StringBuilder(str).reverse().toString();
if ([Link](reversedStr)) {
[Link]("The entered text is a palindrome.");
} else {
[Link]("The entered text is not a palindrome.");
}
[Link]();
}
}
Output:
Palindrome input-Enter a number: 121
121 is a palindrome.
Non palindrome -Enter a number: 123
123 is not a palindrome.
18. Java program to find the factorial of a list of numbers reading
input as command line argument.
class program18{
public static void main(String[] args) {
// Check if any command line arguments are provided
if ([Link] == 0) {
[Link]("No command line arguments found.
Please provide numbers.");
return; // Exit the program if no arguments are provided
}
// Iterate through each command line argument
for (String arg : args) {
try {
// Convert the argument from String to Integer
int num = [Link](arg);
// Calculate the factorial of the number
long factorial = calculateFactorial(num);
// Display the result
[Link]("Factorial of " + num + " is: " +
factorial);
} catch (NumberFormatException e) {
[Link]("Invalid input: " + arg + " is not a valid
integer.");
} catch (IllegalArgumentException e) {
[Link]([Link]());
}
}
}
// Method to calculate factorial
private static long calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not
defined for negative numbers.");
}
long result = 1; // Use long to handle larger factorials
for (int i = 1; i <= n; i++) {
result *= i; // Multiply the result by each number up to n
}
return result;
}
}
Output:
Example 1:- valid
java program18 5 3
Factorial of 5 is: 120
Factorial of 3 is: 6
Example 2:- invalid
java program18 hello -2 4.5
Invalid input: hello is not a valid integer.
Factorial is not defined for negative numbers.
Invalid input: 4.5 is not a valid integer.
19. Java program to display all prime numbers between two.
import [Link];
import [Link];
class Program19 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input validation
[Link]("Enter the lower limit: ");
int lowerLimit = [Link]();
[Link]("Enter the upper limit: ");
int upperLimit = [Link]();
// Ensure lowerLimit is smaller than upperLimit
if (lowerLimit > upperLimit) {
[Link]("Error: Lower limit cannot be greater
than upper limit.");
return;
}
[Link]("Prime numbers between " + lowerLimit + "
and " + upperLimit + " are:");
// Print primes in the range
for (int num = lowerLimit; num <= upperLimit; num++) {
if (isPrime(num)) {
[Link](num + " ");
}
}
[Link]();
}
// Method to check if a number is prime
private static boolean isPrime(int number) {
if (number < 2) {
return false;
}
// Use BigInteger for large numbers
return [Link](number).isProbablePrime(10);
}
}
Output:
Example 1:- Valid range
Enter the lower limit: 10
Enter the upper limit: 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29
Example2:- Edge class
Enter the lower limit: -5
Enter the upper limit: 5
Prime numbers between -5 and 5 are:
235
20. Java program to create a thread using Runnable Interface.
class Program20 implements Runnable {
@Override
public void run() {
[Link]("Inside: " +
[Link]().getName());
}
public static void main(String[] args) {
[Link]("Inside: " +
[Link]().getName());
[Link]("Creating Threads...");
// Creating multiple threads
Thread thread1 = new Thread(new Program20(), "Worker-1");
Thread thread2 = new Thread(new Program20(), "Worker-2");
[Link]("Starting Threads...");
[Link]();
[Link]();
// Ensuring main waits for threads to finish
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
[Link]("All threads completed execution.");
}
}
Output:
Inside: main
Creating Thread...
Starting Thread...
Inside: Thread-0