0% found this document useful (0 votes)
8 views28 pages

Object Oriented Programming Lab: 1.java Program To Display "Hello World" and Display The Size of All The Data Types

The document contains a series of Java programming exercises covering various concepts such as displaying messages, variable types, string operations, control structures, constructors, inheritance, polymorphism, exception handling, and user-defined packages. Each exercise includes code snippets, outputs, and explanations of the functionality implemented. The exercises aim to reinforce understanding of object-oriented programming principles and Java syntax.

Uploaded by

sivakiranvb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views28 pages

Object Oriented Programming Lab: 1.java Program To Display "Hello World" and Display The Size of All The Data Types

The document contains a series of Java programming exercises covering various concepts such as displaying messages, variable types, string operations, control structures, constructors, inheritance, polymorphism, exception handling, and user-defined packages. Each exercise includes code snippets, outputs, and explanations of the functionality implemented. The exercises aim to reinforce understanding of object-oriented programming principles and Java syntax.

Uploaded by

sivakiranvb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

OBJECT ORIENTED PROGRAMMING LAB

1.Java 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"
System.out.println("Hello World!");

// Display the size of all primitive data types


System.out.println("Size of byte: " + Byte.SIZE + " bits");
System.out.println("Size of short: " + Short.SIZE + " bits");
System.out.println("Size of int: " + Integer.SIZE + " bits");
System.out.println("Size of long: " + Long.SIZE + " bits");
System.out.println("Size of float: " + Float.SIZE + " bits");
System.out.println("Size of double: " + Double.SIZE + " bits");
System.out.println("Size of char: " + Character.SIZE + " bits");
System.out.println("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


System.out.println("Static Variable: " + staticVariable);
System.out.println("Instance Variable: " + instanceVariable);
System.out.println("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


example.displayVariables();

// Accessing the static variable directly using class name


System.out.println("Accessing Static Variable from main: " +
Program2.staticVariable);
}
}

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

import java.util.Scanner; // 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(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();

// 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


System.out.println("The maximum number is: " + max);

// Close the scanner


scanner.close();
}
}

Output:
int max = Math.max(num1, Math.max(num2, num3));
5. Java program to check whether the number is odd or even.

import java.util.Scanner; // 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(System.in);

// Prompt the user to enter a number


System.out.print("Enter a number: ");
int num = scanner.nextInt();

// Check if the number is even or odd using the


modulus operator
if (num % 2 == 0) {
System.out.println(num + " is even");
} else {
System.out.println(num + " is odd");
}

// Close the scanner


scanner.close();
}
}

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
}

// Method to display values


public void display() {
System.out.println("Number: " + number);
System.out.println("Text: " + text);
}
}

class Program6 { // Class name corrected


public static void main(String[] args) {
// Creating an object using the default constructor
MyClass obj1 = new MyClass();
System.out.println("Using Default Constructor:");
obj1.display(); // Display default values

// Creating an object using the parameterized constructor


MyClass obj2 = new MyClass(42, "Parameterized Text");
System.out.println("\nUsing Parameterized Constructor:");
obj2.display(); // 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) {
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

8. Java program to implement Single Inheritance.

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.

// 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() {
System.out.println("Duck is walking.");
}
// Implementing the swim method from Swimmable interface
public void swim() {
System.out.println("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
myDuck.walk(); // Output: Duck is walking.
myDuck.swim(); // Output: Duck is swimming.
}
}
Output:
Duck is walking.
Duck is swimming.

10. Java program to implement the Life cycle of the applet.

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.

class Program20 implements Runnable {


@Override
public void run() {
System.out.println("Inside: " +
Thread.currentThread().getName());
}
public static void main(String[] args) {
System.out.println("Inside: " +
Thread.currentThread().getName());
System.out.println("Creating Threads...");
// Creating multiple threads
Thread thread1 = new Thread(new Program20(), "Worker-1");
Thread thread2 = new Thread(new Program20(), "Worker-2");
System.out.println("Starting Threads...");
thread1.start();
thread2.start();
// Ensuring main waits for threads to finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("All threads completed execution.");
}
}

Output:
Inside: main
Creating Thread...
Starting Thread...
Inside: Thread-0

You might also like