Java Experiments
Java Experiments
1
import java.util.Scanner;
public class DiamondStarPattern {
public static void main(String args[]) {
int row, i, j, space = 1;
System.out.print("Enter the number of rows you want to print: ");
Scanner sc = new Scanner(System.in);
row = sc.nextInt();
space = row - 1;
for (j = 1; j<= row; j++) {
for (i = 1; i<= space; i++) {
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++) {
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j<= row - 1; j++) {
for (i = 1; i<= space; i++) {
System.out.print(" ");
}
space++;
for (i = 1; i<= 2 * (row - j) - 1; i++) {
System.out.print("*");
}
System.out.println("");
} } }
// Experiment No. 2
import java.util.Scanner;
class Input {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("Purvika entered " + number);
System.out.println("Java programming is interesting & this is a simple java input
program.");
// closing the scanner object
input.close();
}
}
// Experiment No. 3
import java.util.Scanner;
class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter methods
public String getName() {
return name;
}
public int getAge() {
return age; }
// Method to display person's information
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class PersonInputProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for the first person
System.out.print("Enter name for person 1: ");
String name1 = scanner.nextLine();
System.out.print("Enter age for person 1: ");
int age1 = scanner.nextInt();
scanner.nextLine(); // Consume the newline
// Input for the second person
System.out.print("Enter name for person 2: ");
String name2 = scanner.nextLine();
System.out.print("Enter age for person 2: ");
int age2 = scanner.nextInt();
// Displaying information
System.out.println("\nDisplaying information:");
System.out.println("\nPerson 1 Information:");
person1.displayInfo();
System.out.println("\nPerson 2 Information:");
person2.displayInfo();
scanner.close();
}
}
// Experiment No. 4
public class ShapeCalculator {
// Method Overloading for area calculation
public double calculateArea(double radius) {
return Math.PI * radius * radius; // Circle area
}
// Circle
double circleRadius = 5;
System.out.println("Circle (radius = " + circleRadius + "):");
System.out.println("Area: " + calculator.calculateArea(circleRadius));
System.out.println("Perimeter: " + calculator.calculatePerimeter(circleRadius));
// Rectangle
double length = 10, width = 6;
System.out.println("\nRectangle (length = " + length + ", width = " + width + "):");
System.out.println("Area: " + calculator.calculateArea(length, width));
System.out.println("Perimeter: " + calculator.calculatePerimeter(length, width));
// Triangle
double a = 8, b = 6, c = 10;
System.out.println("\nTriangle (sides = " + a + ", " + b + ", " + c + "):");
System.out.println("Area: " + calculator.calculateArea(a, b, c));
System.out.println("Perimeter: " + calculator.calculatePerimeter(a, b, c));
}
}
// Experiment No. 5
// Matrix addition
import java.util.Scanner;
public class MatrixAddition {
public static void main(String...args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows in matrix : "); //rows and columns in
matrix1 and matrix2 must be same for addition.
int rows = scanner.nextInt();
System.out.print("Enter number of columns in matrix : ");
int columns = scanner.nextInt();
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];
System.out.println("Enter the elements in first matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter the elements in second matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = scanner.nextInt();
}
}
//addition of matrices.
int[][] resultMatix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("\nFirst matrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}
System.out.println("\nSecond matrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}
System.out.println("\nThe sum of the two matrices is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix[i][j] + " ");
}
System.out.println();
}
}
}
// Experiment No. 6
// Matrix subtraction
public class Sub_Matrix
{
public static void main(String[] args) {
int rows, cols;
//Initialize matrix a
int a[][] = {
{9, 5, 6},
{3, 4, 1},
{1, 2, 3}
};
//Initialize matrix b
int b[][] = {
{4, 0, 3},
{2, 3, 1},
{1, 1, 1}
};
}
// experiment
import java.text.DecimalFormat;
@Override
public double calculateReturn() {
double capitalReturn = super.calculateReturn();
double dividendYield = (annualDividend / purchasePrice) * 100;
return capitalReturn + dividendYield;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Annual Dividend: $" + annualDividend);
}
}
@Override
public double calculateReturn() {
double baseReturn = super.calculateReturn();
return baseReturn * (1 + growthRate);
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Growth Rate: " + (growthRate * 100) + "%");
}
}
System.out.println("Regular Stock:");
regularStock.displayInfo();
System.out.println("\nDividend Stock:");
dividendStock.displayInfo();
System.out.println("\nGrowth Stock:");
growthStock.displayInfo();
}
}
// Experiment No. 7
public class StringMethodsExample {
public static void main(String[] args) {
String text = "Hello, World! Welcome to Java Programming Lecture in SIGCE";
// append() method
sb.append("! How are you?");
System.out.println("After append(): " + sb);
// insert() method
sb.insert(5, " Beautiful");
System.out.println("After insert(): " + sb);
// replace() method
sb.replace(6, 15, "Amazing");
System.out.println("After replace(): " + sb);
// reverse() method
sb.reverse();
System.out.println("After reverse(): " + sb);
// capacity() method
System.out.println("Capacity: " + sb.capacity());
// length() method
System.out.println("Length: " + sb.length());
// charAt() method
System.out.println("Character at index 2: " + sb.charAt(2));
// setCharAt() method
sb.setCharAt(0, 'w');
System.out.println("After setCharAt(): " + sb);
// substring() method
String sub = sb.substring(0, 5);
System.out.println("Substring: " + sub);
}
}
// Experiment No. 9
// Single Inheritance
class TechEmployee {
void work() {
System.out.println("Tech Employee is working");
}
}
class Programmer extends TechEmployee {
void code() {
System.out.println("Programmer is coding");
}
}
// Multilevel Inheritance
class SeniorProgrammer extends Programmer {
void reviewCode() {
System.out.println("Senior Programmer is reviewing code");
}
}
// Hierarchical Inheritance
class ProductManager extends TechEmployee {
void createUserStories() {
System.out.println("Product Manager is creating user stories");
}
}
// Interface for Multiple Inheritance
interface CoffeeDrinker {
void drinkCoffee();
}
interface BugFixer {
void fixBugs();
}
// Multiple Inheritance (through interfaces)
class FullStackDeveloper extends TechEmployee implements CoffeeDrinker,
BugFixer {
public void drinkCoffee() {
System.out.println("Full Stack Developer is drinking coffee");
}
public void fixBugs() {
System.out.println("Full Stack Developer is fixing bugs");
}
}
public class InheritanceTypes {
public static void main(String[] args) {
System.out.println("Single Inheritance:");
Programmer programmer = new Programmer();
programmer.work(); // Inherited from TechEmployee
programmer.code();
System.out.println("\nMultilevel Inheritance:");
SeniorProgrammer seniorProgrammer = new SeniorProgrammer();
seniorProgrammer.work(); // Inherited from TechEmployee
seniorProgrammer.code(); // Inherited from Programmer
seniorProgrammer.reviewCode();
System.out.println("\nHierarchical Inheritance:");
ProductManager productManager = new ProductManager();
productManager.work(); // Inherited from TechEmployee
productManager.createUserStories();
// Concrete method
public void displayColor() {
System.out.println("Color: " + color);
}
}
// Concrete subclass
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Another concrete subclass
class Rectangle extends Shape {
private double length;
private double width;
@Override
public double calculateArea() {
return length * width;
}
}
System.out.println("\nRectangle:");
rectangle.displayColor();
System.out.println("Area: " + rectangle.calculateArea());
// Demonstrate polymorphism
Shape shape = circle;
System.out.println("\nShape (Circle):");
shape.displayColor();
System.out.println("Area: " + shape.calculateArea());
shape = rectangle;
System.out.println("\nShape (Rectangle):");
shape.displayColor();
System.out.println("Area: " + shape.calculateArea());
}
}
// Experiment No. 12
class FamilyMember {
protected String name;
protected int age;
protected String role;
public FamilyMember(String name, int age, String role) {
this.name = name;
this.age = age;
this.role = role;
}
public void introduce() {
System.out.println("Hi there, I'm " + name + ", " + age + " years old.");
}
public void describeRole() {
System.out.println("In the family, I am a " + role + ".");
}
}
class Parent extends FamilyMember {
private int numberOfChildren;
public Parent(String name, int age, String role, int numberOfChildren) {
super(name, age, role); // Call to superclass constructor
this.numberOfChildren = numberOfChildren;
}
@Override
public void introduce() {
super.introduce(); // Call to superclass method
System.out.println("I have " + numberOfChildren + " children.");
}
System.out.println("Grandparent:");
grandparent.introduce();
grandparent.describeRole();
System.out.println("\nParent:");
parent.introduce();
parent.describeRole();
parent.parentalDuty();
}
}
// Experiment No. 13
import java.util.Scanner;
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
try {
System.out.print("Enter amount to withdraw: ");
double amount = scanner.nextDouble();
account.withdraw(amount);
} catch (InsufficientFundsException e) {
System.out.println("Exception caught: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out Of Bounds Exception: " +
e.getMessage());
} catch (Exception e) {
System.out.println("Some other exception occurred: " + e.getMessage());
} finally {
System.out.println("This block always executes, regardless of exception
occurrence.");
scanner.close();
}