Programming using Java.
–BCA 6th Sem
Practical File
Programming using Java
Submitted To Submitted By
Mrs. Lalita Name - Akash
Ma'am Section -B
Signature College Roll No. – 98
University Roll No. –
……………………… 221280400092
Session 2024-25
1
INDEX
s.no content Date Signature
1.
write a program on constructor overloading.
2.
Write a program on inheritance.
3.
write a program on interface.
4.
Write a program on polymorphism.
5.
Write a Program on exceptional handling.
6. Write a Program to find the factorial of a
number
7.
Write a Program to print the Fibonacci series
up to n terms.
8.
Write a Program to reverse a number.
9.
Write a Program to check if a number is a
palindrome.
10. Write a Program to find the sum of digits of a
number.
11.
Write a program to find the largest of three
numbers.
12. Write a Program to check whether a number is
prime.
Practical - 1
1.write a program on constructor overloading
// ConstructorOverloadingExample.java
class Student {
String name;
int age;
// Constructor 1: No parameters
Student() {
name = "Unknown";
age = 0;
}
// Constructor 2: One parameter
Student(String studentName) {
name = studentName;
age = 0;
}
// Constructor 3: Two parameters
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class ConstructorOverloadingExample {
public static void main(String[] args) {
// Using different constructors
Student s1 = new Student();
Student s2 = new Student("Rahul");
Student s3 = new Student("Priya", 20);
// Display student details
s1.display();
s2.display();
s3.display();
}
}
Output :
Name: Unknown, Age: 0
Name: Rahul, Age: 0
Name: Priya, Age: 20
Explanation :
Constructor overloading means defining multiple constructors in the same
class with different parameter lists.
In the above example:
* Student() is a default constructor (no arguments).
* Student(String n) accepts only name.
* Student(String n, int a) accepts name and age.
Depending on how the object is created, the appropriate constructor is called.
Practical - 2
2.Write a program on inheritance.
// Base class / Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
void sleep() {
System.out.println("This animal sleeps.");
}
}
// Derived class / Child class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
// Main class
public class InheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
// Calling methods from both base and derived class
d.eat(); // inherited from Animal
d.sleep(); // inherited from Animal
d.bark(); // from Dog class
}
}
Output :
This animal eats food.
This animal sleeps.
The dog barks.
Explanation :
* Inheritance allows a class to use the properties and methods of another class.
* Dog class extends Animal, so it inherits the eat() and sleep() methods.
* The Dog class also has its own method bark().
* In main(), we create a Dog object and call all the methods.
Practical - 3
3.write a program on interface.
// Interface
interface Shape {
void draw(); // abstract method
double getArea(); // abstract method
}
// Implementing class
class Circle implements Shape {
double radius;
Circle(double r) {
radius = r;
}
// Implementing draw method
public void draw() {
System.out.println("Drawing a Circle");
}
// Implementing getArea method
public double getArea() {
return 3.14 * radius * radius;
}
}
// Main class
public class InterfaceExample {
public static void main(String[] args) {
Circle c = new Circle(5.0);
c.draw();
System.out.println("Area of Circle: " + c.getArea());
}
}
Output :
Drawing a Circle
Area of Circle: 78.5
Explanation :
* An interface in Java is like a blueprint—it only has abstract methods (no body).
* The Shape interface has two methods: draw() and getArea().
* The Circle class implements the Shape interface and provides body for both methods.
* In main(), we create a Circle object, call draw(), and print the area.
Practical - 4
4.Write a program on polymorphism.
// Base class
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Derived class 1
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// Derived class 2
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
// Main class
public class PolymorphismExample {
public static void main(String[] args) {
Animal a; // reference of base class
a = new Dog(); // Dog object
a.sound(); // calls Dog's sound()
a = new Cat(); // Cat object
a.sound(); // calls Cat's sound()
}
}
Output :
Dog barks
Cat meows
Expanation :
* Polymorphism means "many forms". In Java, it's achieved through
method overriding and dynamic method dispatch.
* The sound() method is overridden in Dog and Cat classes.
* The reference variable a is of type Animal, but it refers to different
child objects (Dog, Cat), and the correct method is called based on the
object type at runtime.
Practical - 5
5. Write a Program on exceptional handling.
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
int result = a / b;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
catch (Exception e) {
System.out.println("Error: Invalid input.");
}
finally {
System.out.println("Program ended.");
}
sc.close();
}
}
Output :1
Enter first number: 10
Enter second number: 2
Result: 5
Program ended.
Output : 2 (Division by zero)
Enter first number: 10
Enter second number: 0
Error: Cannot divide by zero.
Program ended.
Explanation :
* The program takes two numbers and divides them.
* If the user tries to divide by zero, it throws an ArithmeticException,
which is caught and handled.
* If any other error occurs (like entering text instead of a number),
it goes to the general Exception block.
* The finally block always runs, whether there is an error or not.
Practical - 6
6.Write a Program to find the factorial of a number
import java.util.Scanner;
public class FactorialExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
long factorial = 1;
// Check for negative numbers
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial of " + num + " is: " + factorial);
}
sc.close();
}
}
Output :
Enter a number: 5
Factorial of 5 is: 120
Explanation :
* The program takes a number from the user and calculates its factorial using a for loop.
* It uses a long variable to store the factorial because the value can get large.
* It also handles the case where the number is negative by showing a proper message.
Practical - 7
7. Write a Program to print the Fibonacci series up to n terms.
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
int first = 0, second = 1;
System.out.print("Fibonacci Series: ");
// Printing the Fibonacci series
for (int i = 1; i <= n; i++) {
System.out.print(first + " ");
int nextTerm = first + second;
first = second;
second = nextTerm;
}
sc.close();
}
}
Output :
Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8
Explanation :
* The Fibonacci series starts with 0 and 1. Each subsequent
term is the sum of the previous two terms.
* The program asks for the number of terms (n) to display in the Fibonacci series.
* It then uses a for loop to calculate and print the terms in the series up to n.
Practical -8
8. Write a Program to reverse a number.
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int reversedNumber = 0;
// Reversing the number
while (num != 0) {
int digit = num % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + digit; // Append the digit
num /= 10; // Remove the last digit
}
System.out.println("Reversed Number: " + reversedNumber);
sc.close();
}
}
Output :
Enter a number: 12345
Reversed Number: 54321
Explanation :
* The program takes a number from the user and reverses it using a while loop.
* In each iteration, the last digit of the number is obtained using the modulus
operator (%), and then the reversed number is built by appending this digit.
* The number is reduced by removing its last digit (num /= 10) in each loop iteration.
* The loop continues until the number becomes zero.
Practical - 9
9. Write a Program to check if a number is a palindrome.
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int originalNum = num;
int reversedNumber = 0;
// Reversing the number
while (num != 0) {
int digit = num % 10;
reversedNumber = reversedNumber * 10 + digit;
num /= 10;
}
// Checking if the number is a palindrome
if (originalNum == reversedNumber) {
System.out.println(originalNum + " is a palindrome.");
} else {
System.out.println(originalNum + " is not a palindrome.");
}
sc.close();
}
}
Output :
Enter a number: 121
121 is a palindrome.
Explanation :
* A palindrome number is a number that reads the same forward and backward, like 121 or 12321.
* The program first stores the original number (originalNum) to compare it later.
* Then, it reverses the number using the same approach as the reverse number program.
* Finally, it checks if the original number is equal to the reversed number. If they
are equal, the number is a palindrome; otherwise, it’s not.
Practical - 10
10. Write a Program to find the sum of digits of a number.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
// Finding the sum of digits
while (num != 0) {
int digit = num % 10; // Get the last digit
sum += digit; // Add the digit to sum
num /= 10; // Remove the last digit
}
System.out.println("Sum of digits: " + sum);
sc.close();
}
}
Output :
Enter a number: 1234
Sum of digits: 10
Explanation :
* The program calculates the sum of digits of a number by extracting each
digit using the modulus operator (% 10).
* The number is then reduced by dividing it by 10 (removing the last digit).
* The loop continues until the number becomes zero.
* Each extracted digit is added to the sum variable.
* Finally, it prints the total sum of the digits.
Practical - 11
11. Write a program to find the largest of three numbers.
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = sc.nextInt();
System.out.print("Enter the second number: ");
int num2 = sc.nextInt();
System.out.print("Enter the third number: ");
int num3 = sc.nextInt();
// Finding the largest number
int largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
System.out.println("The largest number is: " + largest);
sc.close();
}
}
Output :
Enter the first number: 12
Enter the second number: 25
Enter the third number: 18
The largest number is: 25
Explanation :
* The program takes three numbers as input from the user.
* It assumes the first number (num1) to be the largest.
* It then compares the second and third numbers with the current largest number and
updates the largest number accordingly.
* Finally, it prints the largest number.
Practical - 12
12. Write a Program to check whether a number is prime.
import java.util.Scanner;
public class PrimeNumberCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
// Check if the number is prime
boolean isPrime = true;
if (num <= 1) {
isPrime = false; // 0 and 1 are not prime
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false; // Divisible by i, not prime
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
sc.close();
}
}
Output :
Enter a number: 17
17 is a prime number.
Explanation :
* A prime number is a number greater than 1 that has no divisors other than 1 and itself.
* The program checks if a number is divisible by any number from 2 to num/2.
If it finds any divisor, the number is not prime.
* If no divisor is found, the number is prime.
* The program handles edge cases such as 0 and 1 (which are not prime).