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

javaprograms-3

The document contains multiple Java programs demonstrating various concepts such as class and object creation, array of objects, constructors, inheritance, method overriding, exception handling, and custom packages. Each program is accompanied by a brief description of its functionality and expected output. The examples illustrate fundamental programming principles in Java, including object-oriented programming techniques.

Uploaded by

sukunansr
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)
6 views

javaprograms-3

The document contains multiple Java programs demonstrating various concepts such as class and object creation, array of objects, constructors, inheritance, method overriding, exception handling, and custom packages. Each program is accompanied by a brief description of its functionality and expected output. The examples illustrate fundamental programming principles in Java, including object-oriented programming techniques.

Uploaded by

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

1.

Implement java program using class and


object.
// Define a class
class StudentList {
// Class attributes
String name;
int age;
// Method to display student
details
void displayDetails() {
System.out.println("Name: " +
name);
System.out.println("Age: " + age);
}
}// Main class
public class Main {
public static void main(String[]
args) {
// Create the first object of the
StudentList class
StudentList student1 = new
StudentList();
student1.name = "Alice";
student1.age = 20;
// Create the second object of
the StudentList class
StudentList student2 = new
StudentList();
student2.name = "Bob";
student2.age = 22;
// Create the third object of the
StudentList class
StudentList student3 = new
StudentList();
student3.name = "Charlie";
student3.age = 19;
// Display details of all students
System.out.println("Student 1:");
student1.displayDetails();
System.out.println("\nStudent
2:");
student2.displayDetails();
System.out.println("\nStudent
3:");
student3.displayDetails();
}
}
2. Implement java program that handle array
of objects.

// Define a class
class Teacher {
// Class attributes
String name;
float salary;
// Constructor to initialize Teacher
attributes
Teacher(String name, float salary) {
this.name = name;
this.salary = salary;
}
// Method to display teacher
details
void displayDetails() {
System.out.println("Name: " +
name);
System.out.println("Salary: " +
salary);
}
}// Main class
public class Main {
public static void main(String[]
args) {
// Create an array of Teacher
objects
Teacher[] teachers = {
new Teacher("Mark", 20000),
new Teacher ("Bob", 22500),
new Teacher ("Freddy", 19000)
};
// Display details of all students
for (int i = 0; i < teachers.length;
i++) {
System.out.println("Teacher "
+ (i + 1) + ":");
teachers[i].displayDetails();
}
}
}
1. Implement java program using class and
object using constructors. (First program
using constructor).

// Define a class to represent a studentclass Student


class StudentList{
// Attributes of the student
String name;
int age;
// Constructor to initialize the
student's attributes
Student(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display student details
void displayDetails() {
System.out.println("Name: " +
name);
System.out.println("Age: " + age);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create objects of the Student
class using the constructor
Student student1 = new
Student("Alice", 20);
Student student2 = new
Student("Bob", 22);
Student student3 = new
Student("Charlie", 19);
// Display details of all students
System.out.println("Student 1:");
student1.displayDetails();
System.out.println("\nStudent 2:");
student2.displayDetails();
System.out.println("\nStudent 3:");
student3.displayDetails();
}
}
3. Implement java program demonstrating
passing and returning objects as
arguments.

// Define the Person class


class Person {
String name; // Field to store the
name of the person
int age; // Field to store the
age of the person

// Constructor to initialize the


person's name
Person(String name,int age) {
this.name = name;
this.age=age;
}
}// Main class with a method to greet
the person and return a Person object
public class Experiment3 {
// Method to greet a Person object
and return the same Person object
static Person greetPerson(Person p)
{
System.out.println("Hello, " +
p.name +",age"+p.age+ "! Welcome to the
program."); // Greet the person
return p; // Return the same
Person object
}
public static void main(String[]
args) {
// Create a Person object
Person person1 = new
Person("Alice",20);
// Pass the person object to the
greetPerson method and get the
result (same object returned)
Person returnedPerson =
greetPerson(person1);
// Print the name of the returned
Person object
System.out.println("Returned
Person's name: " +
returnedPerson.name);
System.out.println("Returned
Person's age: " +
returnedPerson.age);
}
}
4. Implement program based on I/O
operations using I/O classes.

import java.util.Scanner; // Import the Scanner class

public class Main {


public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt and read the student's name
System.out.print("Enter student's name: ");
String name = scanner.nextLine();

// Prompt and read the student's age


System.out.print("Enter student's age: ");
int age = scanner.nextInt();

// Display the input details


System.out.println("\nStudent Details:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);

// Close the scanner


scanner.close();
}
}
5. Java program to demonstrate Constructor
Overloading and Method Overloading.

class Demo {
// Instance variables
int num1, num2;

// Constructor Overloading
Demo() { // Default constructor
num1 = 10; // Assigning a custom value
num2 = 0;
}

Demo(int a) { // Constructor with one


parameter
num1 = a;
num2 = 0;
}

Demo(int a, int b) { // Constructor with two


parameters
num1 = a;
num2 = b;
}

// Method Overloading
void display() { // No parameter
System.out.println("Values: " + num1 + ", "
+ num2);
}

void display(String message) { // One


parameter
System.out.println(message + ": " + num1
+ ", " + num2);
}

public static void main(String[] args) {


// Creating objects using constructor
overloading
Demo obj1 = new Demo(); // Calls
default constructor
Demo obj2 = new Demo(10); // Calls
constructor with one parameter
Demo obj3 = new Demo(20, 30); // Calls
constructor with two parameters

// Calling method overloading


obj1.display(); // Calls display()
without arguments
obj2.display("Single parameter"); // Calls
display() with one argument
obj3.display(); // Calls display()
without arguments
}
}

OUTPUT

Values: 10, 0
Single parameter: 10, 0
Values: 20, 30
6. Program to implement single inheritance in
Java.

// Parent class
class Animal {
// Method in the parent class
void sound() {
System.out.println("Animal makes a
sound");
}
}

// Child class
class Dog extends Animal { // Dog is inheriting
from Animal
// Method in the child class
void bark() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
// Creating an object of the child class Dog
Dog myDog = new Dog();

// Calling method from parent class


(inherited)
myDog.sound(); // Output: Animal makes
a sound

// Calling method from child class


myDog.bark(); // Output: Dog barks
}
}

OUTPUT
Animal makes a sound
Dog barks
7. Java program to implement both multilevel
and hierarchical inheritance in Java.

// Base class (Parent)


class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}

// Multilevel Inheritance: Car inherits Vehicle


class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}

// Multilevel Inheritance: ElectricCar inherits Car


class ElectricCar extends Car {
void charge() {
System.out.println("Electric car is charging");
}
}

// Hierarchical Inheritance: Bike also inherits Vehicle


class Bike extends Vehicle {
void ride() {
System.out.println("Bike is being ridden");
}
}

// Main class
public class Experiment7 {
public static void main(String[] args) {
// Multilevel Inheritance demonstration
(ElectricCar -> Car -> Vehicle)
ElectricCar mycar = new ElectricCar();
mycar.start(); // From Vehicle
mycar.drive(); // From Car
mycar.charge(); // From ElectricCar

System.out.println();

// Hierarchical Inheritance demonstration (Bike


-> Vehicle)
Bike myBike = new Bike();
myBike.start(); // From Vehicle
myBike.ride(); // From Bike
}
}
OUTPUT

Vehicle is starting
Car is driving
Electric car is charging

Vehicle is starting
Bike is being ridden
8. Implement method overriding in java.

class Parent {
void show() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


@Override
void show() {
System.out.println("Child class method");
}
}

public class Main {


public static void main(String[] args) {
Parent obj = new Child(); // Upcasting
obj.show(); // Calls Child's show()
(decided at runtime)
}
}
OUTPUT
Child class method
9. Java program to show multiple inheritance
using interfaces.

// First interface
interface Animal {
void eat();
}

// Second interface
interface Bird {
void fly();
}

// Class implementing both interfaces (Multiple


Inheritance)
class Bat implements Animal, Bird {
public void eat() {
System.out.println("Bat eats insects.");
}

public void fly() {


System.out.println("Bat can fly.");
}
}

// Main class
public class MultipleInheritanceExample {
public static void main(String[] args) {
Bat bat = new Bat();
bat.eat(); // From Animal interface
bat.fly(); // From Bird interface
}
}

OUTPUT
Bat eats insects.
Bat can fly.
10. Java program to implement exception
handling using try-catch.

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an
exception
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot
divide by zero!");
}
System.out.println("Program
continues...");
}
}

OUTPUT
Error: Cannot divide by zero!
Program continues...
11. Program to implement exception
handling using multiple catch.

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
int result = arr[5] / 0; // Causes
ArrayIndexOutOfBoundsException first
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by
zero!");
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: Array index out of
bounds");
}
System.out.println("Program continues");
}
}

OUTPUT
Error: Array index out of bounds
Program continues
12. Write program to implement exception
handling using nested try-catch blocks.

public class NestedTryCatchExample {


public static void main(String[] args) {
try {
System.out.println("Outer try block");

try {
int arr[] = {10, 20, 30};
System.out.println(arr[5]); // Causes
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Inner catch: Array
index out of bounds");
}

int result = 10 / 0; // Causes


ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Outer catch: Cannot
divide by zero");
}

System.out.println("Program continues...");
}
}

OUTPUT
Outer try block
Inner catch: Array index out of bounds
Outer catch: Cannot divide by zero
Program continues...
13. Implement Java program to illustrate
throwing an exception.

public class Experiment13 {


static void checkNumber(int num) {
if (num < 0) {
throw new ArithmeticException("Negative
numbers are not allowed!");
}
System.out.println("Valid number: " + num);
}

public static void main(String[] args) {


checkNumber(10); // Valid input
checkNumber(-5); // This will throw an
exception
System.out.println("Program continues..."); //
This won't execute
}
}
OUTPUT
Valid number: 10
Exception in thread
"main"java.lang.ArithmeticException: Negative
numbers are not allowed!
atExperiment13.checkNumber(Experiment13.java:4)
at Experiment13.main(Experiment13.java:11)

14. Program to create and use a custom


package.

(Code inside Message class which is inside a


package named mypackage)

package mypackage; // Package declaration

public class Message {


public void showMessage() {
System.out.println("Hello from the custom
package!");
}
}

( Code inside Main class which is inside default


package )

import mypackage.Message; // Import custom


package

public class Main {


public static void main(String[] args) {
Message msg = new Message(); // Create
object
msg.showMessage(); // Call method
}
}

OUTPUT
Hello from the custom package!

You might also like