Object Oriented Programming Lab: 1.java Program To Display "Hello World" and Display The Size of All The Data Types
Object Oriented Programming Lab: 1.java Program To Display "Hello World" and Display The Size of All The Data Types
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.
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
// 1. String Length
int lengthOfStr1 = str1.length();
System.out.println("Length of '" + str1 + "': " + lengthOfStr1);
// 2. String Concatenation
String concatenatedString = str1.concat(" ").concat(str2);
System.out.println("Concatenated String: " +
concatenatedString);
// 3. Substring
String substring = concatenatedString.substring(0, 5); //
Extracting "Hello"
System.out.println("Substring: " + substring);
}
}
Output:
Length of 'Hello': 5
Concatenated String: Hello World
Substring: Hello
4. Java program to find the maximum of three numbers.
Output:
int max = Math.max(num1, Math.max(num2, num3));
5. Java program to check whether the number is odd or even.
Output:
1.Enter a number: 8
8 is even
2.Enter 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
}
Output:
Using Default Constructor:
Number: 0
Text: Default Text
class Student {
// Instance variables
int id;
String name;
// Constructor to initialize the student object
public Student(int id, String name) {
this.id = id;
this.name = name;
}
// Method to display student details
public void display() {
System.out.println("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) {
student.display();
}
}
}
Output:
ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie
class Animal {
// Method in the parent class
public void eat() {
System.out.println("Animal is eating");
}
}
// Child class that extends the Animal class
class Dog extends Animal {
// Method in the child class
public void bark() {
System.out.println("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
myDog.eat(); // Output: Animal is eating
// Call the method from Dog class
myDog.bark(); // Output: Dog is barking
}
}
Output:
Animal is eating
Dog is barking
9.Java program to implement Multiple Inheritance using
Interface.
import javax.swing.*;
import java.awt.*;
public class Program10 extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello, World!", 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
Program10 panel = new Program10();
frame.add(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
appletviewer program10.java
11.Java 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;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("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 = calculator.add(3, 7);
System.out.println("Sum of integers: " + intSum); // Output: 10
// Adding two float numbers without default values
float floatSum = calculator.add(3.5f, 2.5f);
System.out.println("Sum of floats: " + floatSum); // Output: 6.0
// Adding two integers with default values
int defaultIntSum = calculator.add();
System.out.println("Sum of integers with default values: " +
defaultIntSum); // Output: 15
// Adding two float numbers with one default value
float defaultFloatSum = calculator.add(4.5f);
System.out.println("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() {
System.out.println("Animal makes a sound");
}
}
// Child classes with method overriding
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}
class Cow extends Animal {
@Override
public void sound() {
System.out.println("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) {
animal.sound();
}
}
}
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 java.util.Scanner;
class Program14 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the array size: ");
int size = scanner.nextInt();
if (size < 0) {
System.out.println("Error: Array size cannot be negative.");
} else {
int[] array = new int[size];
System.out.println("Array of size " + size + " created
successfully.");
}
System.out.println("Continuing execution...");
scanner.close();
}
}
Output:
Error: Attempted to create an array with a negative size.
java.lang.NegativeArraySizeException: -5
at program14.main(program14.java:6) // 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 java.util.Scanner;
class Program15 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine(); // Read user input
if (str == null || str.isEmpty()) {
System.out.println("Error: String is null or empty.");
} else {
System.out.println("Length of the string: " + str.length());
}
System.out.println("Execution completed. Please check your
variables.");
scanner.close();
}
}
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() {
System.out.println("Hello from the Greeting class!");
}
}
Output:
Hello from the Greeting class!
17. Java program to check whether a number is palindrome or
not.
import java.util.Scanner;
class Program17 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt for number input
System.out.print("Enter a number: ");
int originalNum = scanner.nextInt();
// Reject negative numbers
if (originalNum < 0) {
System.out.println(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) {
System.out.println(originalNum + " is a palindrome.");
} else {
System.out.println(originalNum + " is not a palindrome.");
}
}
// Prompt for string input
System.out.print("\nEnter a word or phrase: ");
scanner.nextLine(); // Consume newline
String str = scanner.nextLine().replaceAll("[^a-zA-Z0-9]",
"").toLowerCase(); // Normalize input
// Check if the string is a palindrome
String reversedStr = new StringBuilder(str).reverse().toString();
if (str.equals(reversedStr)) {
System.out.println("The entered text is a palindrome.");
} else {
System.out.println("The entered text is not a palindrome.");
}
scanner.close();
}
}
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 (args.length == 0) {
System.out.println("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 = Integer.parseInt(arg);
// Calculate the factorial of the number
long factorial = calculateFactorial(num);
// Display the result
System.out.println("Factorial of " + num + " is: " +
factorial);
} catch (NumberFormatException e) {
System.out.println("Invalid input: " + arg + " is not a valid
integer.");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
// 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 java.util.Scanner;
import java.math.BigInteger;
class Program19 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input validation
System.out.print("Enter the lower limit: ");
int lowerLimit = scanner.nextInt();
System.out.print("Enter the upper limit: ");
int upperLimit = scanner.nextInt();
// Ensure lowerLimit is smaller than upperLimit
if (lowerLimit > upperLimit) {
System.out.println("Error: Lower limit cannot be greater
than upper limit.");
return;
}
System.out.println("Prime numbers between " + lowerLimit + "
and " + upperLimit + " are:");
// Print primes in the range
for (int num = lowerLimit; num <= upperLimit; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
scanner.close();
}
// 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 BigInteger.valueOf(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.
Output:
Inside: main
Creating Thread...
Starting Thread...
Inside: Thread-0