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

Practical Assignment 3

The document contains multiple Java programs demonstrating various concepts such as string operations, constructors, method overloading and overriding, keywords (static, final, super, this), exception handling, and the differences between final, finally, and finalize. Each section includes code examples and their corresponding outputs to illustrate the functionality. Overall, it serves as a comprehensive guide for understanding fundamental Java programming concepts.

Uploaded by

anshpatel1093
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)
4 views

Practical Assignment 3

The document contains multiple Java programs demonstrating various concepts such as string operations, constructors, method overloading and overriding, keywords (static, final, super, this), exception handling, and the differences between final, finally, and finalize. Each section includes code examples and their corresponding outputs to illustrate the functionality. Overall, it serves as a comprehensive guide for understanding fundamental Java programming concepts.

Uploaded by

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

1.

Write a JAVA program to Implement string operations using


Stringclass, StringBuffer class & toString method.
Program:

public class StringOperations {

public static void main(String[] args) {


// Using String class
String str1 = "Hello";
String str2 = "World";

// Concatenation
String str3 = str1 + " " + str2;
System.out.println("Concatenated String: " + str3);

// Length
System.out.println("Length of str1: " + str1.length());

// Substring
System.out.println("Substring of str1: " + str1.substring(1, 4));

// Character at a position
System.out.println("Character at position 2 in str2: " + str2.charAt(2));

// Uppercase
System.out.println("Uppercase str1: " + str1.toUpperCase());

// Replace
System.out.println("Replace 'l' with 'p' in str1: " + str1.replace('l', 'p'));

// Using StringBuffer class


StringBuffer sb = new StringBuffer("Hello");

// Append
sb.append(" World");
System.out.println("Appended StringBuffer: " + sb.toString());

// Insert
sb.insert(5, ",");
System.out.println("Inserted StringBuffer: " + sb.toString());

// Reverse
sb.reverse();
System.out.println("Reversed StringBuffer: " + sb.toString());

// Delete
sb.delete(0, 6);
System.out.println("Deleted StringBuffer: " + sb.toString());

// Replace
sb.replace(0, sb.length(), "Goodbye World");
System.out.println("Replaced StringBuffer: " + sb.toString());

// Using toString method


String strFromBuffer = sb.toString();
System.out.println("String from StringBuffer using toString: " + strFromBuffer);
}
}
Output:
Concatenated String: Hello World
Length of str1: 5
Substring of str1: ell
Character at position 2 in str2: r
Uppercase str1: HELLO
Replace 'l' with 'p' in str1: Heppo
Appended StringBuffer: Hello World
Inserted StringBuffer: Hello, World
Reversed StringBuffer: dlroW ,olleH
Deleted StringBuffer: ,olleH
Replaced StringBuffer: Goodbye World
String from StringBuffer using toString: Goodbye World

2. Write a JAVA program to Implement of constructor, constructor


overloading,
Program:

public class ConstructorExample {

// Instance variables
private String name;
private int age;

// Default constructor
public ConstructorExample() {
this.name = "Unknown";
this.age = 0;
System.out.println("Default constructor called");
}

// Parameterized constructor with one parameter


public ConstructorExample(String name) {
this.name = name;
this.age = 0;
System.out.println("Constructor with name called");
}

// Parameterized constructor with two parameters


public ConstructorExample(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Constructor with name and age called");
}
// Method to display the details
public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {


// Using default constructor
ConstructorExample person1 = new ConstructorExample();
person1.display();

// Using constructor with one parameter


ConstructorExample person2 = new ConstructorExample("Alice");
person2.display();

// Using constructor with two parameters


ConstructorExample person3 = new ConstructorExample("Bob", 25);
person3.display();
}
}

Output:
Default constructor called
Name: Unknown, Age: 0
Constructor with name called
Name: Alice, Age: 0
Constructor with name and age called
Name: Bob, Age: 25
3. Write a JAVA program to Implement Method overloading, Method
overriding.
Program:

// Base class
class Animal {
// Method to be overridden
public void sound() {
System.out.println("Animal makes a sound");
}
}

// Derived class
class Dog extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println("Dog barks");
}
}

// Class demonstrating method overloading


class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


public double add(double a, double b) {
return a + b;
}
}

public class MethodOverloadingOverriding {

public static void main(String[] args) {


// Demonstrating method overloading
Calculator calculator = new Calculator();
System.out.println("Sum of 2 and 3: " + calculator.add(2, 3));
System.out.println("Sum of 2, 3 and 4: " + calculator.add(2, 3, 4));
System.out.println("Sum of 2.5 and 3.5: " + calculator.add(2.5, 3.5));

// Demonstrating method overriding


Animal animal = new Animal();
animal.sound(); // Calls the method from Animal class

Dog dog = new Dog();


dog.sound(); // Calls the overridden method from Dog class

// Demonstrating polymorphism with method overriding


Animal polymorphicDog = new Dog();
polymorphicDog.sound(); // Calls the overridden method from Dog class
}
}

Output:
Sum of 2 and 3: 5
Sum of 2, 3 and 4: 9
Sum of 2.5 and 3.5: 6.0
Animal makes a sound
Dog barks
Dog barks
4. Write a JAVA program to Implement Static Keyword, Final keyword, Super
keyword, this keyword.
Program:

// Parent class demonstrating final and super keywords


class Parent {
// final variable
final int finalVar = 100;

// final method
final void displayFinal() {
System.out.println("This is a final method in Parent class.");
}

// method to be overridden
void show() {
System.out.println("Parent class show() method.");
}
}

// Child class inheriting Parent class


class Child extends Parent {
// instance variable
int var;

// Constructor using 'this' keyword


Child(int var) {
this.var = var;
}

// Overriding show method


@Override
void show() {
super.show(); // using super keyword to call parent class method
System.out.println("Child class show() method.");
}

// method to display variable using this keyword


void display() {
System.out.println("Value of var: " + this.var);
}
}

// Class demonstrating static keyword


class StaticDemo {
// static variable
static int staticVar;

// static method
static void staticMethod() {
System.out.println("This is a static method.");
}

// static block
static {
staticVar = 10;
System.out.println("Static block executed. Value of staticVar: " + staticVar);
}
}

// Main class
public class KeywordDemo {
public static void main(String[] args) {
// Demonstrating static keyword
StaticDemo.staticMethod();
System.out.println("Accessing static variable: " + StaticDemo.staticVar);

// Demonstrating final keyword


Parent parent = new Parent();
parent.displayFinal();
// parent.finalVar = 200; // This will cause a compilation error because finalVar is final

// Demonstrating super and this keywords


Child child = new Child(50);
child.show();
child.display();
}
}

Output:
Static block executed. Value of staticVar: 10
This is a static method.
Accessing static variable: 10
This is a final method in Parent class.
Parent class show() method.
Child class show() method.
Value of var: 50
5. Write a JAVA program to Implement Try-catch block - Throw and Throws.
Program:

public class ExceptionHandlingDemo {


public static void main(String[] args) {
// Using try-catch block
try {
int result = divide(10, 0); // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
}

// Using throw keyword


try {
validateAge(15); // This will throw an exception
} catch (IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
}

// Using throws keyword


try {
checkNumber(-5); // This will throw an exception
} catch (Exception e) {
System.out.println("Caught an Exception: " + e.getMessage());
}
}

// Method using throws keyword


public static void checkNumber(int number) throws Exception {
if (number < 0) {
throw new Exception("Number must be non-negative.");
}
System.out.println("Number is valid: " + number);
}

// Method using throw keyword


public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Age is valid: " + age);
}

// Method using try-catch block


public static int divide(int a, int b) {
return a / b;
}
}
Output:
Caught an ArithmeticException: / by zero
Caught an IllegalArgumentException: Age must be 18 or older.
Caught an Exception: Number must be non-negative.

6. Write a JAVA program to Implement Final vs Finally vs Finalize.


Program:
class FinalDemo {
// final variable
final int finalVar = 10;

// final method
final void display() {
System.out.println("This is a final method.");
}
}

// Class that cannot be inherited because it is declared final


final class FinalClass {
void show() {
System.out.println("This is a final class.");
}
}

class FinalizeDemo {
// Override finalize method
@Override
protected void finalize() throws Throwable {
System.out.println("Finalize method called.");
super.finalize();
}
}

public class FinalFinallyFinalizeDemo {


public static void main(String[] args) {
// Demonstrating final
FinalDemo finalDemo = new FinalDemo();
System.out.println("Final variable value: " + finalDemo.finalVar);
finalDemo.display();

// Demonstrating finally
try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}

// Demonstrating finalize
FinalizeDemo finalizeDemo = new FinalizeDemo();
finalizeDemo = null; // Eligible for garbage collection
System.gc(); // Requesting JVM to call garbage collector

System.out.println("Main method completed.");


}
}

Output:
Final variable value: 10
This is a final method.
Caught an ArithmeticException: / by zero
Finally block executed.
Main method completed.
Finalize method called.

You might also like