Java Exp21-25
Java Exp21-25
Experiment 21:
Aim : Write a Program to accept two integers as inputs and print their sum.
Source code:
import java.util.Scanner;
Output:
Experiment 22:
Aim: Write a program illustrating all uses of super keywords.
Source code:
class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void sound() {
super.sound();
System.out.println("Dog barks");
}
public void printName() {
System.out.println("Name of dog: " + super.name);
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.sound();
dog.printName();
}
}
Output:
Experiment 23:
Aim: Create an abstract class shape. Let rectangle and triangle inherit this shape class. Add
necessary functions.
Source code:
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
class Triangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a triangle");
}
}
public class ShapeTest {
public static void main(String[] args) {
Shape shape1 = new Rectangle();
Shape shape2 = new Triangle();
shape1.draw();
shape2.draw();
}
}
Output:
Experiment 24:
Aim: Write an application that creates an ‘interface’ and implements it.
Source code:
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound();
}
}
Output:
Experiment 25:
Aim : Write a Program to take care of Number Format Exception if user enters values other
than integer for calculating average marks of 2 students. The name of the students and marks
in 3 subjects are taken from the user while executing the program. In the same Program write
your own Exception classes to take care of Negative values and values out of range (i.e. other
than in the range of 0-100).
Source code:
import java.util.Scanner;
class InvalidMarksException extends Exception {
public InvalidMarksException(String message) {
super(message);
}
}
try {
for (int i = 1; i <= 2; i++) {
System.out.print("Enter name of student " + i + ":");
String name = scanner.nextLine();
System.out.println("Enter marks of 3 subjects for " + name + ":");
int totalMarks = 0;
for (int j = 1; j <= 3; j++) {
totalMarks += getValidMarks(scanner);
}
} catch (InvalidMarksException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Invalid input! Please enter valid integers.");
} finally {
scanner.close();
}
}