0% found this document useful (0 votes)
14 views9 pages

Java Area Calculations and Exceptions

The document contains multiple Java experiments demonstrating various programming concepts such as area calculations for different shapes using method overloading, exception handling, and user input processing. It includes examples of classes, constructors, abstract classes, custom exceptions, and multithreading. Additionally, it showcases string manipulation methods and applet creation for user input display.

Uploaded by

nucleyaverma
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)
14 views9 pages

Java Area Calculations and Exceptions

The document contains multiple Java experiments demonstrating various programming concepts such as area calculations for different shapes using method overloading, exception handling, and user input processing. It includes examples of classes, constructors, abstract classes, custom exceptions, and multithreading. Additionally, it showcases string manipulation methods and applet creation for user input display.

Uploaded by

nucleyaverma
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

EXPERIMENT 1

public class Main { void Area(float side) {


public static void main(String[] args) { [Link]("Area of the Square: "
Rectangle obj = new Rectangle(); + side * side);
[Link](30, 20); // Area of rectangle }
[Link](12.5, 4.5); // Area of rectangle }

Circle obj1 = new Circle(); class Circle {


[Link](3); // Area of circle static final double PI = [Link];
[Link](5.5); // Area of circle
// Overloaded function to calculate the area
Square obj2 = new Square(); of the circle (takes a double parameter)
[Link](20); // Area of square void Area(double r) {
[Link](5.2); // Area of square double A = PI * r * r;
} [Link]("The area of the
} circle is: " + A);
}
class Square {
// Overloaded function to calculate the area // Overloaded function to calculate the area
of the square (takes a double parameter) of the circle (takes a float parameter)
void Area(double side) { void Area(float r) {
[Link]("Area of the Square: " double A = PI * r * r;
+ side * side); [Link]("The area of the
} circle is: " + A);
}
// Overloaded function to calculate the area }
of the square (takes a float parameter)

class Rectangle {
// Overloaded function to calculate
the area of the rectangle
void Area(double length, double
width) {
[Link]("Area of the
rectangle: " + length * width);
}
}
[Link]("Student Id: " +
[Link]);
EXPERIMENT:2 [Link]("Student Name:
public class Student { " + [Link]);
int id; }
String name; }

// Default constructor (no EXPERIMENT:3


parameters) // Abstract class Dimension
Student() { abstract class Dimension {
[Link]("This is the // Abstract method to calculate the
default constructor."); area of a rectangle
} abstract double rectangle(double
length, double width);
// Parameterized constructor (with
parameters) // Abstract method to calculate the
Student(int i, String n) { area of a triangle
id = i; abstract double triangle(double base,
name = n; double height);
} }

public static void main(String[] args) { // Main class to implement the


// Creating objects using different Dimension abstract class
constructors public class Main {
Student defaultStudent = new public static void main(String[] args) {
Student(); // Default constructor // Create an instance of Dimension
[Link]("\nDefault (you can't directly instantiate an abstract
Constructor values:"); class)
[Link]("Student Id: " + Dimension shape = new
[Link]); Dimension() {
[Link]("Student Name: @Override
" + [Link]); double rectangle(double length,
double width) {
Student parameterizedStudent = return length * width;
new Student(10, "David"); // }
Parameterized constructor
@Override
[Link]("\nParameterized double triangle(double base,
Constructor values:"); double height) {
return 0.5 * base * height;
} }
}; O/P: Error: / by zero
b) IOException
// Calculate and display the area of import [Link].*;
a rectangle
double rectLength = 10.0; public class IOExceptionExample {
double rectWidth = 5.0; public static void main(String[] args) {
double rectArea = try {
[Link](rectLength, rectWidth); FileReader fileReader = new
[Link]("Rectangle FileReader("[Link]"); // File not
Area: " + rectArea); found
int data = [Link]();
// Calculate and display the area of [Link]("Read data: "
a triangle + data);
double triBase = 8.0; } catch (IOException e) {
double triHeight = 6.0; [Link]("Error: " +
double triArea = [Link]());
[Link](triBase, triHeight); }
[Link]("Triangle Area: }
" + triArea); }
}
} o/p: Error: [Link] (No such file
or directory)
EXPERIMENT:4
a) Arithmatic exception
public class
ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int numerator = 10;
int denominator = 0;
int result = numerator /
denominator; // Division by zero
[Link]("Result: " +
result);
} catch (ArithmeticException e) {
[Link]("Error: " +
[Link]());
}
}
static int getUserInputAge() {
// For demonstration purposes,
EXPERIMENT:5 return a fixed age (you can replace this
// Custom exception class for invalid age with actual input)
class InvalidAgeException extends return 20;
Exception { }
public InvalidAgeException(String }
message) {
super(message); EXPERIMENT: 6
} import [Link].*;
}
public class SumCalculator {
public class Main { public static void main(String[] args) {
public static void main(String[] args) { try {
try { // Create a DataInputStream to
int userAge = read input from the console
getUserInputAge(); // Assume this DataInputStream dataInput =
method gets the user's input age new DataInputStream([Link]);
validateAge(userAge); // Validate
the age // Prompt the user to enter the
[Link]("Welcome! first number
You are " + userAge + " years old."); [Link]("Enter the first
} catch (InvalidAgeException ex) { number: ");
[Link]("Invalid age: " double num1 =
+ [Link]()); [Link]([Link]
} e());
}
// Prompt the user to enter the
// Validate the user's input age second number
static void validateAge(int age) throws [Link]("Enter the
InvalidAgeException { second number: ");
if (age < 18) { double num2 =
throw new [Link]([Link]
InvalidAgeException("Age must be 18 e());
or older.");
} // Calculate the sum
} double sum = num1 + num2;

// Simulate getting user input (replace // Display the result


with actual input logic)
[Link]("Sum of " + // Output: h
num1 + " and " + num2 + " is: " + sum);
} catch (IOException e) { 5. length():
[Link]("Error
reading input: " + [Link]()); String s = "Sachin";
} [Link]([Link]());
} // Output: 6
}
6. intern():
EXPERIMENT:7
1. toUpperCase() and toLowerCase(): String s = new String("Sachin");
String s2 = [Link]();
String s = "Sachin"; [Link](s2);
[Link]([Link]()); // // Output: Sachin
Output: SACHIN
[Link]([Link]()); // 7. valueOf():

Output: sachin int num = 42;


String numStr = [Link](num);
2. trim(): [Link](numStr);
// Output: 42
String s = " Sachin ";
[Link]([Link]()); EXPERIMENT: 8
// Output: Sachin import [Link];

public class
3. startsWith() and endsWith(): StringConcatenationExample {
public static void main(String[] args) {
String s = "Sachin"; Scanner scanner = new
[Link]([Link]("Sa")); Scanner([Link]);
// Output: true
[Link]([Link]("n")); [Link]("Enter the first
// Output: true string: ");
String firstString =
4. charAt(int index): [Link]();

String s = "Sachin"; [Link]("Enter the second


[Link]([Link](0)); string: ");
// Output: S String secondString =
[Link]([Link](3)); [Link]();
public static void main(String[] args) {
// Concatenate the strings PrintThread aiThread = new
String concatenatedString = PrintThread("AI", 2000);
[Link](secondString); PrintThread aiMlThread = new
PrintThread("AI&ML", 5000);
[Link]("Concatenated
string: " + concatenatedString); [Link]();
[Link]();
[Link](); // Close the }
scanner to release resources }
}
} EXPERIMENT: 10
import [Link];
EXPERIMENT: 9
class PrintThread extends Thread { public class
private final String message; ProducerConsumerExample {
private final long sleepTime; public static void main(String[] args)
throws InterruptedException {
public PrintThread(String message, final PC pc = new PC();
long sleepTime) {
[Link] = message; Thread producerThread = new
[Link] = sleepTime; Thread(() -> {
} try {
[Link]();
@Override } catch (InterruptedException e)
public void run() { {
try { [Link]();
for (int i = 1; i <= 5; i++) { }
[Link](message + });
" " + i);
[Link](sleepTime); Thread consumerThread = new
} Thread(() -> {
} catch (InterruptedException e) { try {
[Link]("Thread [Link]();
interrupted: " + [Link]()); } catch (InterruptedException e)
} {
} [Link]();
} }
});
public class Main {
[Link]();
[Link](); [Link]("Consumer
consumed: " + val);
[Link](); notify();
[Link](); [Link](1000);
} }
}
static class PC { }
private final LinkedList<Integer> }
list = new LinkedList<>(); }
private final int capacity = 2;
EXPERIMENT: 11
public void produce() throws import [Link];
InterruptedException { import [Link];
int value = 0;
while (true) { public class UserInputApplet extends
synchronized (this) { Applet {
while ([Link]() == capacity) private String name;
wait(); private int age;
private String address;

[Link]("Producer produced: public void init() {


" + value); // Initialize default values
[Link](value++); name = "";
notify(); age = 0;
[Link](1000); address = "";
} }
}
} public void paint(Graphics g) {
// Display input fields
public void consume() throws [Link]("Enter Name:", 20,
InterruptedException { 30);
while (true) { [Link]("Enter Age:", 20, 60);
synchronized (this) { [Link]("Enter Address:", 20,
while ([Link]() == 0) 90);
wait();
// Display user input
int val = [Link](); [Link]("Name: " + name,
150, 30);
[Link]("Age: " + age, 150, 60);
[Link]("Address: " + address,
150, 90);
}

public String getParameter(String


parameterName) {
// Get parameters from HTML file
(if any)
if ([Link]("name"))
{
return name;
} else if
([Link]("age")) {
return [Link](age);
} else if
([Link]("address")) {
return address;
}
return null;
}

public void start() {


// Retrieve parameters from
HTML (if provided)
name = getParameter("name");
try {
age =
[Link](getParameter("age"));
} catch (NumberFormatException
e) {
age = 0; // Default value if age is
not provided or invalid
}
address = getParameter("address");
}
}

You might also like