Java_Programs
Java_Programs
Java_Programs
class Car {
String brand;
String model;
int year;
void displayInfo() {
System.out.println(year + " " + brand + " " + model);
}
car1.displayInfo();
car2.displayInfo();
}
}
Output:
2020 Toyota Corolla
2022 Honda Civic
class MathOperations {
int add(int a, int b) {
return a + b;
}
Output:
Overloaded Method (2 args): 15
Overloaded Method (3 args): 30
Overridden Method: 30
interface Animal {
void makeSound();
void eat();
}
dog.makeSound();
dog.eat();
cat.makeSound();
cat.eat();
}
}
Output:
Dog barks
Dog eats bones
Cat meows
Cat drinks milk
class Animal {
String name = "Animal";
void makeSound() {
System.out.println("Animal makes a sound");
}
}
void displayNames() {
System.out.println("Parent Name: " + super.name);
System.out.println("Child Name: " + name);
}
@Override
void makeSound() {
super.makeSound();
System.out.println("Dog barks");
}
Output:
Parent Name: Animal
Child Name: Dog
Animal makes a sound
Dog barks
Dog is sleeping
Output:
Hello from MyClass in mypackage!
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds.");
}
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Error: Null reference encountered.");
}
Output:
Error: Division by zero is not allowed.
Error: Array index out of bounds.
Error: Null reference encountered.
Program execution continues...
try {
validateAge(20);
} catch (InvalidAgeException e) {
System.out.println("Exception Caught: " + e.getMessage());
}
}
}
Output:
Exception Caught: Age must be 18 or above to vote.
You are eligible to vote.