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

Java Experiments

Java all experiments Semester 3, object oriented programming with java, programs, with output, explanation and syntax

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Java Experiments

Java all experiments Semester 3, object oriented programming with java, programs, with output, explanation and syntax

Uploaded by

purvikajagtap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

// Experiment No.

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();

// Creating Person objects


Person person1 = new Person(name1, age1);
Person person2 = new Person(name2, age2);

// 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
}

public double calculateArea(double length, double width) {


return length * width; // Rectangle area
}

public double calculateArea(double a, double b, double c) {


// Triangle area using Heron's formula
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}

// Method Overloading for perimeter calculation


public double calculatePerimeter(double radius) {
return 2 * Math.PI * radius; // Circle perimeter
}

public double calculatePerimeter(double length, double width) {


return 2 * (length + width); // Rectangle perimeter
}

public double calculatePerimeter(double a, double b, double c) {


return a + b + c; // Triangle perimeter
}

public static void main(String[] args) {


ShapeCalculator calculator = new ShapeCalculator();

// 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}
};

//Calculates number of rows and columns present in given matrix


rows = a.length;
cols = a[0].length;
//Array diff will hold the result
int diff[][] = new int[rows][cols];

//Performs subtraction of matrices a and b. Store the result in matrix diff


for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
diff[i][j] = a[i][j] - b[i][j];
}
}

System.out.println("Subtraction of two matrices: ");


for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
System.out.print(diff[i][j] + " ");
}
System.out.println();
}
}
}
// Matrix Multiplication
public class MatrixMultiplication{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}

}
// experiment
import java.text.DecimalFormat;

// Base Stock class


class Stock {
protected String symbol;
protected double purchasePrice;
protected double currentPrice;

public Stock(String symbol, double purchasePrice, double currentPrice) {


this.symbol = symbol;
this.purchasePrice = purchasePrice;
this.currentPrice = currentPrice;
}

public double calculateReturn() {


return (currentPrice - purchasePrice) / purchasePrice * 100;
}

public void displayInfo() {


DecimalFormat df = new DecimalFormat("#.##");
System.out.println("Stock: " + symbol);
System.out.println("Purchase Price: $" + purchasePrice);
System.out.println("Current Price: $" + currentPrice);
System.out.println("Return: " + df.format(calculateReturn()) + "%");
}
}

// Dividend Stock subclass


class DividendStock extends Stock {
private double annualDividend;

public DividendStock(String symbol, double purchasePrice, double currentPrice,


double annualDividend) {
super(symbol, purchasePrice, currentPrice);
this.annualDividend = annualDividend;
}

@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);
}
}

// Growth Stock subclass


class GrowthStock extends Stock {
private double growthRate;

public GrowthStock(String symbol, double purchasePrice, double currentPrice,


double growthRate) {
super(symbol, purchasePrice, currentPrice);
this.growthRate = growthRate;
}

@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) + "%");
}
}

public class StockOverridingExample {


public static void main(String[] args) {
Stock regularStock = new Stock("REG", 100, 110);
DividendStock dividendStock = new DividendStock("DIV", 50, 55, 2);
GrowthStock growthStock = new GrowthStock("GRO", 200, 220, 0.1);

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";

// 1. length() - returns the length of the string


System.out.println("1. Length of the string: " + text.length());

// 2. charAt() - returns the character at a specific index


System.out.println("2. Character at index 7: " + text.charAt(7));

// 3. substring() - extracts a substring


System.out.println("3. Substring from index 7 to 12: " + text.substring(7, 12));

// 4. toLowerCase() and toUpperCase() - change case


System.out.println("4. Lowercase: " + text.toLowerCase());
System.out.println(" Uppercase: " + text.toUpperCase());

// 5. trim() - removes leading and trailing whitespace


String paddedText = " Trimmed ";
System.out.println("5. Trimmed: '" + paddedText.trim() + "'");

// 6. replace() - replaces all occurrences of a character


System.out.println("6. Replacing 'o' with '0': " + text.replace('o', '0'));

// 7. contains() - checks if the string contains a sequence


System.out.println("7. Contains 'Java': " + text.contains("Java"));

// 8. startsWith() and endsWith() - check start and end of string


System.out.println("8. Starts with 'Hello': " + text.startsWith("Hello"));
System.out.println(" Ends with 'Programming.': " +
text.endsWith("Programming."));

// 9. split() - splits the string into an array


String[] words = text.split(" ");
System.out.print("9. Words in the string: ");
for (String word : words) {
System.out.print(word + ", ");
}
System.out.println();

// 10. indexOf() - finds the index of a character or substring


System.out.println("10. Index of 'Purvika': " + text.indexOf("Purvika"));
}
}
// Experiment No. 8

public class StringBufferDemo {


public static void main(String[] args) {
// Create a new StringBuffer
StringBuffer sb = new StringBuffer("Hello Buddies!!I'm Purvika Jagtap");
System.out.println("Original: " + sb);

// 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);

// delete() method - first example


sb.delete(5, 13);
System.out.println("After first delete(): " + sb);

// delete() method - second example (new)


sb.delete(sb.indexOf("!"), sb.length());
System.out.println("After second delete(): " + 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();

System.out.println("\nMultiple Inheritance (through interfaces):");


FullStackDeveloper fullStackDev = new FullStackDeveloper();
fullStackDev.work(); // Inherited from TechEmployee
fullStackDev.drinkCoffee(); // Implemented from CoffeeDrinker interface
fullStackDev.fixBugs(); // Implemented from BugFixer interface
}
}
// Experiment No. 10
// Interface 1: Defines data storage functionality
interface DataStorage {
void saveData(String data); // Method to save data
}
// Interface 2: Defines data processing functionality
interface DataProcessing {
void processData(); // Method to process data
}
// Class that implements both interfaces: handling both storage and processing
class DataHandler implements DataStorage, DataProcessing {
private String storedData;
// Implementing the saveData() method of DataStorage interface
@Override
public void saveData(String data) {
this.storedData = data;
System.out.println("Data saved: " + data);
}
// Implementing the processData() method of DataProcessing interface
@Override
public void processData() {
if (storedData != null) {
System.out.println("Processing data: " + storedData);
} else {
System.out.println("No data to process.");
}
}
}
public class Main {
public static void main(String[] args) {
// Creating an instance of DataHandler
DataHandler handler = new DataHandler();
// Saving data
handler.saveData("Sample data for analysis");
// Processing the saved data
handler.processData();
}
}
// Experiment No. 11
// Abstract class
abstract class Shape {
protected String color;
// Constructor
public Shape(String color) {
this.color = color;
}
// Abstract method
public abstract double calculateArea();

// 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;

public Rectangle(String color, double length, double width) {


super(color);
this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
// Create instances of concrete classes
Circle circle = new Circle("Red", 5.0);
Rectangle rectangle = new Rectangle("Blue", 4.0, 6.0);

// Use abstract and concrete methods


System.out.println("Circle:");
circle.displayColor();
System.out.println("Area: " + circle.calculateArea());

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.");
}

public void parentalDuty() {


System.out.println(name + " is helping with homework.");
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
FamilyMember grandparent = new FamilyMember("Satyaketu", 60,
"grandfather");
Parent parent = new Parent("Monica", 30, "mother", 2);

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;

public BankAccount(double initialBalance) {


this.balance = initialBalance;
}

public void withdraw(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds. Current balance is "
+ balance);
}
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}
}

public class ExceptionHandlingDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankAccount account = new BankAccount(1000);

try {
System.out.print("Enter amount to withdraw: ");
double amount = scanner.nextDouble();

account.withdraw(amount);

// This line will throw ArithmeticException if amount is 0


double result = 100 / amount;
System.out.println("100 divided by " + amount + " is " + result);

// This will throw ArrayIndexOutOfBoundsException


int[] arr = new int[5];
arr[10] = 50;

} 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();
}

System.out.println("Program continues after exception handling.");


}
}
// Experiment No. 14
import java.util.Scanner;
// Custom exception for underage users
class UnderAgeException extends Exception {
public UnderAgeException(String message) {
super(message);
}
}
// Custom exception for overage users
class OverAgeException extends Exception {
public OverAgeException(String message) {
super(message);
}
}
class AgeVerifier {
private static final int MIN_AGE = 18;
private static final int MAX_AGE = 65;
public static void verifyAge(int age) throws UnderAgeException,
OverAgeException {
if (age < MIN_AGE) {
throw new UnderAgeException("You must be at least " + MIN_AGE + " years
old to use this service.");
} else if (age > MAX_AGE) {
throw new OverAgeException("You must be under " + MAX_AGE + " years
old to use this service.");
}
System.out.println("Age verified successfully. Welcome to the service!");
}
}
public class UserDefinedException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Please enter your age: ");
int userAge = scanner.nextInt();
AgeVerifier.verifyAge(userAge);
} catch (UnderAgeException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("This service is not suitable for minors.");
} catch (OverAgeException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("This service has an upper age limit for participation.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Thank you for using our age verification system.");
}
}
}
// Experiment No. 15
class NumPrint implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}
}
public class ThreadClass {
public static void main(String[] args) {
System.out.println("Main thread starting");
// Create a new thread
Thread numberThread = new Thread(new NumPrint());
// Start the thread
numberThread.start();
// Main thread continues execution
for (int i = 1; i <= 5; i++) {
System.out.println("Main: " + i);
try {
Thread.sleep(1000); // Sleep for 1000 milliseconds
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
// Wait for the number thread to finish
try {
numberThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting");
}
System.out.println("Main thread ending");
}
}

You might also like