0% found this document useful (0 votes)
6 views45 pages

Java Priyansh

The document contains a series of Java lab assignments covering various programming concepts such as data types, loops, decision control statements, classes and objects, and strings. Each section includes sample code demonstrating specific tasks like temperature conversion, Fibonacci series generation, prime number checking, and class creation for rectangles and students. The assignments are structured to help students practice and understand fundamental programming principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views45 pages

Java Priyansh

The document contains a series of Java lab assignments covering various programming concepts such as data types, loops, decision control statements, classes and objects, and strings. Each section includes sample code demonstrating specific tasks like temperature conversion, Fibonacci series generation, prime number checking, and class creation for rectangles and students. The assignments are structured to help students practice and understand fundamental programming principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA LAB ASSIGNMENT

Submitted by: Priyansh Kushwaha Submitted to: Mrs. Sonali Karone


Ma’am
Roll No.: IT-2k22-37

1. DATA TYPES
[Link] a java program to demonstrate the use of different data types (int, float. double ,
char, boolean, etc.).

public class DataTypesDemo {

public static void main(String[] args) {


// Integer data type
int intVariable = 42;
[Link]("Integer: " + intVariable);

// Float data type


float floatVariable = 3.14f;
[Link]("Float: " + floatVariable);

// Double data type


double doubleVariable = 3.14159265359;
[Link]("Double: " + doubleVariable);

// Character data type


char charVariable = 'A';
[Link]("Character: " + charVariable);

// Boolean data type


boolean booleanVariable = true;
[Link]("Boolean: " + booleanVariable);
}
}

2. Create a program to convert a given temperature in celsius to fahrenheit and vice-


versa.

import [Link];
public class TemperatureConverter {

// Method to convert Celsius to Fahrenheit


public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}

// Method to convert Fahrenheit to Celsius


public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter temperature: ");
double temperature = [Link]();

[Link]("Is this temperature in (C)elsius or (F)ahrenheit? Enter C or F: ");


char unit = [Link]().charAt(0);

// Converting temperature based on user input


if (unit == 'C' || unit == 'c') {
double fahrenheit = celsiusToFahrenheit(temperature);
[Link]("%.2f Celsius is %.2f Fahrenheit%n", temperature, fahrenheit);
} else if (unit == 'F' || unit == 'f') {
double celsius = fahrenheitToCelsius(temperature);
[Link]("%.2f Fahrenheit is %.2f Celsius%n", temperature, celsius);
} else {
[Link]("Invalid unit entered. Please enter C for Celsius or F for
Fahrenheit.");
}

[Link]();
}
}

3. Develop a program to perform arithmetic operations using various data types and
demonstrate type casting.

public class ArithmeticOperations {


public static void main(String[] args) {
// Integer arithmetic
int int1 = 10;
int int2 = 3;
int intResult = int1 / int2;
[Link]("Integer division: " + int1 + " / " + int2 + " = " + intResult);

// Double arithmetic
double double1 = 10.0;
double double2 = 3.0;
double doubleResult = double1 / double2;
[Link]("Double division: " + double1 + " / " + double2 + " = " + doubleResult);

// Float arithmetic
float float1 = 10.0f;
float float2 = 3.0f;
float floatResult = float1 / float2;
[Link]("Float division: " + float1 + " / " + float2 + " = " + floatResult);

// Character arithmetic (casting char to int)


char char1 = 'A'; // ASCII value of 'A' is 65
char char2 = 3;
int charResult = char1 + char2;
[Link]("Character arithmetic: " + char1 + " + " + char2 + " = " + (char)
charResult);

// Boolean operations are not possible directly in arithmetic context

// Type casting examples


// Integer to double
double castedDouble = int1;
[Link]("Casted integer to double: " + castedDouble);

// Double to integer (truncates the decimal part)


int castedInt = (int) double1;
[Link]("Casted double to integer: " + castedInt);

// Float to integer (truncates the decimal part)


int castedFloatToInt = (int) float1;
[Link]("Casted float to integer: " + castedFloatToInt);

// Arithmetic with casting


double mixedResult = int1 + double1;
[Link]("Mixed arithmetic (int + double): " + mixedResult);
}
}

2. LOOPS
1. Write a program to print the fibonacci series up to a given number using loops.

import [Link];

public class FibonacciSeries {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter the number up to which you want the Fibonacci series: ");
int number = [Link]();

int num1 = 0, num2 = 1;


[Link]("Fibonacci Series up to " + number + ":");

// Printing the Fibonacci series


while (num1 <= number) {
[Link](num1 + " ");

// Calculate the next number


int nextNum = num1 + num2;
num1 = num2;
num2 = nextNum;
}

[Link]();
}
}

2. Create a program to find the factorial of a number using both for and while loops.

import [Link];

public class Factorial {


// Method to find factorial using a for loop
public static long factorialForLoop(int number) {
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
return factorial;
}

// Method to find factorial using a while loop


public static long factorialWhileLoop(int number) {
long factorial = 1;
int i = 1;
while (i <= number) {
factorial *= i;
i++;
}
return factorial;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter a number to find its factorial: ");
int number = [Link]();

// Calculate factorial using for loop


long factorialFor = factorialForLoop(number);
[Link]("Factorial of " + number + " using for loop: " + factorialFor);

// Calculate factorial using while loop


long factorialWhile = factorialWhileLoop(number);
[Link]("Factorial of " + number + " using while loop: " + factorialWhile);

[Link]();
}
}

3. Develop a program to generate a multiplication table for a given number using loops.

import [Link];
public class MultiplicationTable {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter the number for which you want the multiplication table: ");
int number = [Link]();

// Printing multiplication table


[Link]("Multiplication Table for " + number + ":");
for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}

[Link]();
}
}

[Link] CONTROL STATEMENTS


1. Write a program to check whether a given number is prime or not using if-else
statements.

import [Link];

public class PrimeCheck {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter a number to check if it's prime: ");
int number = [Link]();

boolean isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}

// Checking if the number is prime


if (isPrime) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}

[Link]();
}
}

2. Create a program to calculate a grade of a student based on marks using switch-case


statements.

import [Link];

public class GradeCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter the marks of the student: ");
int marks = [Link]();

// Calculating grade based on marks


String grade;
switch (marks / 10) {
case 10:
case 9:
grade = "A";
break;
case 8:
grade = "B";
break;
case 7:
grade = "C";
break;
case 6:
grade = "D";
break;
case 5:
grade = "E";
break;
default:
grade = "F";
break;
}

// Displaying the grade


[Link]("The grade for marks " + marks + " is: " + grade);

[Link]();
}
}

3. Develop a program to check if a given year is a leap year or not.

import [Link];

public class LeapYearChecker {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Asking user for input


[Link]("Enter a year to check if it's a leap year: ");
int year = [Link]();

// Checking if the year is a leap year


boolean isLeapYear = false;

// Leap year conditions


if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) {
isLeapYear = true;
} else {
isLeapYear = false;
}
} else {
isLeapYear = true;
}
} else {
isLeapYear = false;
}

// Displaying the result


if (isLeapYear) {
[Link](year + " is a leap year.");
} else {
[Link](year + " is not a leap year.");
}

[Link]();
}
}

4. CLASSES AND OBJECTS


1. Write a program to create a class called `Rectangle` with methods to calculate area and
perimeter.

public class Rectangle {


// Declare the attributes (width and height)
private double width;
private double height;

// Constructor to initialize width and height


public Rectangle(double width, double height) {
[Link] = width;
[Link] = height;
}

// Method to calculate the area of the rectangle


public double area() {
return width * height;
}

// Method to calculate the perimeter of the rectangle


public double perimeter() {
return 2 * (width + height);
}
// Main method to test the Rectangle class
public static void main(String[] args) {
// Create a Rectangle object
Rectangle rectangle = new Rectangle(5.0, 3.0);

// Print the area and perimeter of the rectangle


[Link]("Area: " + [Link]()); // Area = width * height
[Link]("Perimeter: " + [Link]()); // Perimeter = 2 * (width + height)
}
}

2. Create a class `Student` with attributes like name, roll number, and marks. Implement
methods to calculate the average and display student details.

public class Student {


// Attributes of the class
private String name;
private int rollNumber;
private double[] marks;

// Constructor to initialize the student details


public Student(String name, int rollNumber, double[] marks) {
[Link] = name;
[Link] = rollNumber;
[Link] = marks;
}

// Method to calculate the average of marks


public double calculateAverage() {
double total = 0;
for (double mark : marks) {
total += mark;
}
return total / [Link];
}

// Method to display student details


public void displayStudentDetails() {
[Link]("Student Name: " + name);
[Link]("Roll Number: " + rollNumber);
[Link]("Marks: ");
for (double mark : marks) {
[Link](mark + " ");
}
[Link]("\nAverage Marks: " + calculateAverage());
}

// Main method to test the Student class


public static void main(String[] args) {
// Marks array for the student
double[] marks = {85.5, 90.0, 78.5, 88.0};

// Create a Student object


Student student = new Student("John Doe", 101, marks);

// Display student details


[Link]();
}
}

3. Develop a class `Complex` to represent complex numbers and implement methods for
addition and subtraction of complex numbers.

public class Complex {


// Attributes to represent the real and imaginary parts of the complex number
private double real;
private double imaginary;

// Constructor to initialize the real and imaginary parts


public Complex(double real, double imaginary) {
[Link] = real;
[Link] = imaginary;
}

// Method to add two complex numbers


public Complex add(Complex other) {
double realPart = [Link] + [Link];
double imaginaryPart = [Link] + [Link];
return new Complex(realPart, imaginaryPart);
}

// Method to subtract two complex numbers


public Complex subtract(Complex other) {
double realPart = [Link] - [Link];
double imaginaryPart = [Link] - [Link];
return new Complex(realPart, imaginaryPart);
}

// Method to display the complex number in the form "a + bi"


public void display() {
[Link]([Link] + " + " + [Link] + "i");
}

// Main method to test the Complex class


public static void main(String[] args) {
// Create two Complex objects
Complex complex1 = new Complex(3.5, 2.5);
Complex complex2 = new Complex(1.5, 4.5);

// Display the complex numbers


[Link]("Complex Number 1: ");
[Link]();
[Link]("Complex Number 2: ");
[Link]();

// Add the complex numbers


Complex sum = [Link](complex2);
[Link]("Sum: ");
[Link]();

// Subtract the complex numbers


Complex difference = [Link](complex2);
[Link]("Difference: ");
[Link]();
}
}

5. STRINGS
1. Write a program to check if a given string is a palindrome.

import [Link];

public class PalindromeChecker {


// Method to check if a given string is a palindrome
public static boolean isPalindrome(String str) {
// Remove spaces and convert to lowercase for uniform comparison
str = [Link]("\\s", "").toLowerCase();

// Use two-pointer approach to check if the string is a palindrome


int start = 0;
int end = [Link]() - 1;

while (start < end) {


if ([Link](start) != [Link](end)) {
return false; // Characters don't match, not a palindrome
}
start++;
end--;
}

return true; // All characters matched, it's a palindrome


}

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Ask the user for a string input


[Link]("Enter a string: ");
String input = [Link]();

// Check if the string is a palindrome and print the result


if (isPalindrome(input)) {
[Link](input + " is a palindrome.");
} else {
[Link](input + " is not a palindrome.");
}

// Close the scanner to prevent resource leak


[Link]();
}
}

2. Create a program to count the number of vowels and consonants in a string.

import [Link];
public class VowelConsonantCounter {

// Method to count vowels and consonants in a string


public static void countVowelsAndConsonants(String str) {
// Convert the string to lowercase to handle both uppercase and lowercase letters
str = [Link]();

// Initialize counters for vowels and consonants


int vowelCount = 0;
int consonantCount = 0;

// Loop through each character in the string


for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);

// Check if the character is a letter


if ([Link](ch)) {
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
} else {
consonantCount++;
}
}
}

// Output the results


[Link]("Vowels: " + vowelCount);
[Link]("Consonants: " + consonantCount);
}

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Ask the user to input a string


[Link]("Enter a string: ");
String input = [Link]();

// Call the method to count vowels and consonants


countVowelsAndConsonants(input);

// Close the scanner to prevent resource leak


[Link]();
}
}

import [Link];

public class VowelConsonantCounter {

// Method to count vowels and consonants in a string


public static void countVowelsAndConsonants(String str) {
// Convert the string to lowercase to handle both uppercase and lowercase letters
str = [Link]();

// Initialize counters for vowels and consonants


int vowelCount = 0;
int consonantCount = 0;

// Loop through each character in the string


for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);

// Check if the character is a letter


if ([Link](ch)) {
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
} else {
consonantCount++;
}
}
}

// Output the results


[Link]("Vowels: " + vowelCount);
[Link]("Consonants: " + consonantCount);
}

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Ask the user to input a string


[Link]("Enter a string: ");
String input = [Link]();
// Call the method to count vowels and consonants
countVowelsAndConsonants(input);

// Close the scanner to prevent resource leak


[Link]();
}
}

3. Develop a program to find and replace a substring within a string.

import [Link];

public class FindAndReplaceSubstring {

public static void main(String[] args) {


// Create a scanner object to take user input
Scanner scanner = new Scanner([Link]);

// Input the original string


[Link]("Enter the original string: ");
String originalString = [Link]();

// Input the substring to find


[Link]("Enter the substring to find: ");
String substringToFind = [Link]();

// Input the substring to replace with


[Link]("Enter the replacement substring: ");
String replacementSubstring = [Link]();

// Find and replace the substring


String modifiedString = [Link](substringToFind, replacementSubstring);

// Output the modified string


[Link]("\nOriginal String: " + originalString);
[Link]("Modified String: " + modifiedString);

// Close the scanner


[Link]();
}
}
6. WRAPPER CLASSES
1. Write a program to convert primitive data types into objects using wrapper classes.

public class WrapperClassExample {

public static void main(String[] args) {


// Convert primitive types to wrapper class objects

// int to Integer
int intValue = 42;
Integer intObject = [Link](intValue); // Using valueOf() method
[Link]("Integer object: " + intObject);

// char to Character
char charValue = 'A';
Character charObject = [Link](charValue); // Using valueOf() method
[Link]("Character object: " + charObject);

// boolean to Boolean
boolean booleanValue = true;
Boolean booleanObject = [Link](booleanValue); // Using valueOf() method
[Link]("Boolean object: " + booleanObject);

// double to Double
double doubleValue = 3.14;
Double doubleObject = [Link](doubleValue); // Using valueOf() method
[Link]("Double object: " + doubleObject);

// float to Float
float floatValue = 9.81f;
Float floatObject = [Link](floatValue); // Using valueOf() method
[Link]("Float object: " + floatObject);

// long to Long
long longValue = 123456789L;
Long longObject = [Link](longValue); // Using valueOf() method
[Link]("Long object: " + longObject);

// byte to Byte
byte byteValue = 100;
Byte byteObject = [Link](byteValue); // Using valueOf() method
[Link]("Byte object: " + byteObject);
// short to Short
short shortValue = 10;
Short shortObject = [Link](shortValue); // Using valueOf() method
[Link]("Short object: " + shortObject);

// Autoboxing: Automatically converting primitive types to objects


Integer autoBoxedInt = intValue; // Autoboxing (primitive int to Integer object)
[Link]("Autoboxed Integer: " + autoBoxedInt);
}
}

2. Create a program to perform arithmetic operations on two numbers using wrapper classes.

import [Link];

public class ArithmeticOperations {


public static void main(String[] args) {
// Creating Scanner object for user input
Scanner scanner = new Scanner([Link]);

// Taking input as strings and converting them to Integer objects


[Link]("Enter the first number: ");
Integer num1 = [Link]([Link]());

[Link]("Enter the second number: ");


Integer num2 = [Link]([Link]());

// Performing arithmetic operations


Integer sum = [Link](num1 + num2);
Integer difference = [Link](num1 - num2);
Integer product = [Link](num1 * num2);

// Handling division by zero case


Integer quotient = (num2 != 0) ? [Link](num1 / num2) : null;

// Displaying results
[Link]("Sum: " + sum);
[Link]("Difference: " + difference);
[Link]("Product: " + product);

if (quotient != null) {
[Link]("Quotient: " + quotient);
} else {
[Link]("Division by zero is not allowed.");
}

// Closing the scanner object


[Link]();
}
}

3. Develop a program to compare two Integer objects using wrapper class methods.

import [Link];

public class IntegerComparison {


public static void main(String[] args) {
// Creating a Scanner object for user input
Scanner scanner = new Scanner([Link]);

// Taking input as strings and converting them to Integer objects


[Link]("Enter the first integer: ");
Integer num1 = [Link]([Link]());

[Link]("Enter the second integer: ");


Integer num2 = [Link]([Link]());

// Using equals() method


if ([Link](num2)) {
[Link]("The two Integer objects are equal.");
} else {
[Link]("The two Integer objects are not equal.");
}

// Using compareTo() method


int result = [Link](num2);
if (result == 0) {
[Link]("Using compareTo(): The two Integer objects are equal.");
} else if (result > 0) {
[Link]("Using compareTo(): The first Integer object is greater.");
} else {
[Link]("Using compareTo(): The second Integer object is greater.");
}

// Using compare() method (static method)


int comparison = [Link](num1, num2);
if (comparison == 0) {
[Link]("Using compare(): The two Integer objects are equal.");
} else if (comparison > 0) {
[Link]("Using compare(): The first Integer object is greater.");
} else {
[Link]("Using compare(): The second Integer object is greater.");
}

// Closing the scanner object


[Link]();
}
}

7. INHERITANCE
1. Write a program to demonstrate single inheritance with a base class `Animal` and a derived
class `Dog`.

// Base class
class Animal {
// Method of the base class
void eat() {
[Link]("Animal is eating.");
}

void sleep() {
[Link]("Animal is sleeping.");
}
}

// Derived class
class Dog extends Animal {
// Method of the derived class
void bark() {
[Link]("Dog is barking.");
}
}

// Main class to test the inheritance


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

// Calling methods from both the base class and the derived class
[Link](); // Inherited method from Animal
[Link](); // Inherited method from Animal
[Link](); // Method of Dog class
}
}

2. Create a program to implement multilevel inheritance with a base class `Person`, derived
class `Employee`, and further derived class `Manager`.

// Base class
class Person {
String name;
int age;

// Constructor of Person class


Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Method of Person class


void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

// Derived class (inherits from Person)


class Employee extends Person {
String employeeId;
String department;

// Constructor of Employee class


Employee(String name, int age, String employeeId, String department) {
super(name, age); // Calling the constructor of Person class
[Link] = employeeId;
[Link] = department;
}

// Method of Employee class


void displayEmployeeInfo() {
displayInfo(); // Calling method of Person class
[Link]("Employee ID: " + employeeId);
[Link]("Department: " + department);
}
}

// Further derived class (inherits from Employee)


class Manager extends Employee {
String team;

// Constructor of Manager class


Manager(String name, int age, String employeeId, String department, String team) {
super(name, age, employeeId, department); // Calling the constructor of Employee class
[Link] = team;
}

// Method of Manager class


void displayManagerInfo() {
displayEmployeeInfo(); // Calling method of Employee class
[Link]("Team: " + team);
}
}

// Main class to test the multilevel inheritance


public class MultilevelInheritanceDemo {
public static void main(String[] args) {
// Creating an object of Manager class
Manager manager = new Manager("Alice", 35, "EMP123", "Sales", "Sales Team A");

// Displaying information using the Manager class object


[Link]();
}
}

3. Develop a program to implement hierarchical inheritance with a base class `Shape` and
derived classes `Circle` and `Rectangle`.

import [Link];

// Base class
class Shape {
// Method of the base class
void display() {
[Link]("This is a shape.");
}
}

// Derived class (inherits from Shape)


class Circle extends Shape {
double radius;

// Constructor of Circle class


Circle(double radius) {
[Link] = radius;
}

// Method to calculate the area of the circle


double calculateArea() {
return [Link] * radius * radius;
}

// Method to display the area of the circle


void displayArea() {
[Link]("Area of the Circle: " + calculateArea());
}
}

// Derived class (inherits from Shape)


class Rectangle extends Shape {
double length;
double width;

// Constructor of Rectangle class


Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}

// Method to calculate the area of the rectangle


double calculateArea() {
return length * width;
}

// Method to display the area of the rectangle


void displayArea() {
[Link]("Area of the Rectangle: " + calculateArea());
}
}

// Main class to test hierarchical inheritance


public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Creating an object of Circle class


[Link]("Enter the radius of the circle: ");
double radius = [Link]();
Circle circle = new Circle(radius);

// Creating an object of Rectangle class


[Link]("Enter the length of the rectangle: ");
double length = [Link]();
[Link]("Enter the width of the rectangle: ");
double width = [Link]();
Rectangle rectangle = new Rectangle(length, width);

// Displaying information
[Link]("\nCircle Information:");
[Link](); // Method inherited from Shape
[Link](); // Method specific to Circle

[Link]("\nRectangle Information:");
[Link](); // Method inherited from Shape
[Link](); // Method specific to Rectangle

// Closing the scanner


[Link]();
}
}

8. INTERFACES AND PACKAGES


1. Write a program to implement an interface `Printable` and demonstrate its use in a class
`Document`.
import [Link];

// Define the interface


interface Printable {
void print();
}

// Implement the interface in a class


class Document implements Printable {
private String content;

public Document(String content) {


[Link] = content;
}

@Override
public void print() {
[Link]("Printing document content: " + content);
}
}

// Demonstrate its use in a main class


public class Main {
public static void main(String[] args) {
Document doc = new Document("Hello, world!");
[Link](); // Output: Printing document content: Hello, world!
}
}

2. Create a package `shapes` containing classes `Circle`, `Square`, and `Triangle`. Write a
program to use these classes from the package.

//create a circle class in package

package shapes;

public class Circle {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

public double getArea() {


return [Link] * radius * radius;
}
public double getPerimeter() {
return 2 * [Link] * radius;
}
}

//create the square class in java

package shapes;

public class Square {


private double side;

public Square(double side) {


[Link] = side;
}

public double getArea() {


return side * side;
}

public double getPerimeter() {


return 4 * side;
}
}

//create triangle class

package shapes;

public class Triangle {


private double base;
private double height;

public Triangle(double base, double height) {


[Link] = base;
[Link] = height;
}

public double getArea() {


return 0.5 * base * height;
}

public double getPerimeter(double side1, double side2, double side3) {


return side1 + side2 + side3;
}
}

//create the main program

import [Link];
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(5);
[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " + [Link]());

Square square = new Square(4);


[Link]("Square Area: " + [Link]());
[Link]("Square Perimeter: " + [Link]());

Triangle triangle = new Triangle(6, 8);


[Link]("Triangle Area: " + [Link]());
[Link]("Triangle Perimeter: " + [Link](5, 6, 7));
}
}

3. Develop a program to implement multiple inheritance using interfaces.

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

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

// Class that implements both interfaces


class Eagle implements Animal, Bird {
@Override
public void sound() {
[Link]("Eagle makes a screeching sound");
}
@Override
public void fly() {
[Link]("Eagle flies high in the sky");
}

public static void main(String[] args) {


Eagle eagle = new Eagle();
[Link]();
[Link]();
}
}

9. EXCEPTION HANDLING
1. Write a program to handle `ArithmeticException` and `ArrayIndexOutOfBoundsException`.

public class ExceptionHandlingExample {

public static void main(String[] args) {


try {
// Attempting to divide by zero, which will throw ArithmeticException
int result = 10 / 0;
[Link]("Result: " + result);

// Attempting to access an invalid array index, which will throw


ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
[Link]("Number: " + numbers[3]);
} catch (ArithmeticException e) {
[Link]("ArithmeticException: Cannot divide by zero!");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: Array index is out of bounds!");
} finally {
[Link]("This block always executes");
}
}
}

2. Create a program to demonstrate the use of `try-catch-finally` blocks.

public class TryCatchFinallyExample {


public static void main(String[] args) {
try {
// Code that may throw an exception
int[] array = {1, 2, 3};
[Link]("Element at index 3: " + array[3]); // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
// Handling the exception
[Link]("Exception caught: " + e);
} finally {
// This block will always execute
[Link]("Finally block executed.");
}

// This line will execute whether an exception occurs or not


[Link]("Rest of the code...");
}
}

3. Develop a program to create a custom exception and handle it using a `throw` and `throws`
clause.

//Define a Custom Exception:

// Custom Exception class


class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

//Use the Custom Exception in a Program

public class CustomExceptionExample {

// Method that throws the custom exception


public static void checkValue(int value) throws CustomException {
if (value < 0) {
throw new CustomException("Value cannot be negative!");
} else {
[Link]("Value is: " + value);
}
}
public static void main(String[] args) {
try {
checkValue(5); // This will not throw an exception
checkValue(-1); // This will throw an exception
} catch (CustomException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("Finally block executed.");
}

[Link]("Rest of the code...");


}
}

10. MULTITHREADING
1. Write a program to create a thread by extending `Thread` class and another by implementing
`Runnable` interface.
// Extending Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread running by extending Thread class.");
for (int i = 1; i <= 5; i++) {
[Link](i + " from MyThread");
}
}
}

// Implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
[Link]("Thread running by implementing Runnable interface.");
for (int i = 1; i <= 5; i++) {
[Link](i + " from MyRunnable");
}
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating thread by extending Thread class
MyThread thread1 = new MyThread();
[Link]();

// Creating thread by implementing Runnable interface


Thread thread2 = new Thread(new MyRunnable());
[Link]();
}
}

2. Create a program to demonstrate thread synchronization using synchronized methods.

// Shared resource class


class Counter {
private int count = 0;

// Synchronized method to increment the count


public synchronized void increment() {
count++;
}

// Method to get the count


public int getCount() {
return count;
}
}

// Thread class that uses the Counter


class CounterThread extends Thread {
private Counter counter;

public CounterThread(Counter counter) {


[Link] = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
[Link]();
}
}
}

public class SynchronizationExample {


public static void main(String[] args) {
Counter counter = new Counter();
// Creating two threads that share the same Counter instance
CounterThread thread1 = new CounterThread(counter);
CounterThread thread2 = new CounterThread(counter);

// Starting both threads


[Link]();
[Link]();

// Waiting for both threads to finish


try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}

// Displaying the final count


[Link]("Final count: " + [Link]());
}
}

3. Develop a program to implement inter-thread communication using `wait()` and `notify()`


methods.

class SharedResource {
private int data;
private boolean dataAvailable = false;

public synchronized void produce(int value) throws InterruptedException {


while (dataAvailable) {
wait();
}
data = value;
dataAvailable = true;
[Link]("Produced: " + value);
notify();
}

public synchronized void consume() throws InterruptedException {


while (!dataAvailable) {
wait();
}
[Link]("Consumed: " + data);
dataAvailable = false;
notify();
}
}

class Producer extends Thread {


private SharedResource resource;

public Producer(SharedResource resource) {


[Link] = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) {
try {
[Link](i);
[Link](1000); // Simulate time taken to produce
} catch (InterruptedException e) {
[Link]();
}
}
}
}

class Consumer extends Thread {


private SharedResource resource;

public Consumer(SharedResource resource) {


[Link] = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) {
try {
[Link]();
[Link](1500); // Simulate time taken to consume
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class InterThreadCommunicationExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

Producer producer = new Producer(resource);


Consumer consumer = new Consumer(resource);

[Link]();
[Link]();
}
}

11. APPLETS AND AWT


1. Write an applet to draw geometric shapes like circles, rectangles, and lines.

import [Link];
import [Link];

public class GeometricShapesApplet extends Applet {


public void paint(Graphics g) {
// Draw a rectangle
[Link](50, 50, 100, 50); // (x, y, width, height)

// Draw a circle
[Link](200, 50, 50, 50); // (x, y, width, height)

// Draw a line
[Link](50, 150, 150, 150); // (x1, y1, x2, y2)
}
}

import [Link];
import [Link];
import [Link];

public class GeometricShapesSwing extends JPanel {

@Override
protected void paintComponent(Graphics g) {
[Link](g);
// Draw a rectangle
[Link](50, 50, 100, 50); // (x, y, width, height)
// Draw a circle
[Link](200, 50, 50, 50); // (x, y, width, height)

// Draw a line
[Link](50, 150, 150, 150); // (x1, y1, x2, y2)
}

public static void main(String[] args) {


JFrame frame = new JFrame("Geometric Shapes");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 300);
[Link](new GeometricShapesSwing());
[Link](true);
}
}

2. Create a simple calculator using AWT components like buttons, text fields, and labels.

import [Link].*;
import [Link].*;

public class SimpleCalculator extends Frame implements ActionListener {


// Components of the calculator
TextField number1, number2, result;
Button addButton, subtractButton, multiplyButton, divideButton;
Label label1, label2, labelResult;

// Constructor to setup the GUI components


public SimpleCalculator() {
// Create labels
label1 = new Label("Number 1:");
[Link](50, 50, 80, 30);
label2 = new Label("Number 2:");
[Link](50, 100, 80, 30);
labelResult = new Label("Result:");
[Link](50, 150, 80, 30);

// Create text fields


number1 = new TextField();
[Link](150, 50, 100, 30);
number2 = new TextField();
[Link](150, 100, 100, 30);
result = new TextField();
[Link](150, 150, 100, 30);
[Link](false);

// Create buttons
addButton = new Button("+");
[Link](50, 200, 50, 30);
subtractButton = new Button("-");
[Link](110, 200, 50, 30);
multiplyButton = new Button("*");
[Link](170, 200, 50, 30);
divideButton = new Button("/");
[Link](230, 200, 50, 30);

// Add action listeners to buttons


[Link](this);
[Link](this);
[Link](this);
[Link](this);

// Add components to the frame


add(label1);
add(number1);
add(label2);
add(number2);
add(labelResult);
add(result);
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);

// Frame properties
setSize(350, 300);
setLayout(null);
setVisible(true);
}

// Action performed method


public void actionPerformed(ActionEvent e) {
double num1 = [Link]([Link]());
double num2 = [Link]([Link]());
double res = 0;
if ([Link]() == addButton) {
res = num1 + num2;
} else if ([Link]() == subtractButton) {
res = num1 - num2;
} else if ([Link]() == multiplyButton) {
res = num1 * num2;
} else if ([Link]() == divideButton) {
res = num1 / num2;
}

[Link]([Link](res));
}

public static void main(String[] args) {


new SimpleCalculator();
}
}

3. Develop an applet to create a login form with AWT components.

import [Link];
import [Link].*;
import [Link].*;

public class LoginFormApplet extends Applet implements ActionListener {


TextField usernameField, passwordField;
Button loginButton;
Label messageLabel;

public void init() {


// Set layout
setLayout(new GridLayout(4, 2));

// Create components
Label usernameLabel = new Label("Username:");
Label passwordLabel = new Label("Password:");
usernameField = new TextField();
passwordField = new TextField();
[Link]('*'); // Hide password characters
loginButton = new Button("Login");
messageLabel = new Label("");
// Add action listener to the login button
[Link](this);

// Add components to the applet


add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(new Label("")); // Empty label for alignment
add(loginButton);
add(messageLabel);
}

public void actionPerformed(ActionEvent e) {


String username = [Link]();
String password = [Link]();

// Simple login validation


if ("user".equals(username) && "pass".equals(password)) {
[Link]("Login successful!");
} else {
[Link]("Invalid username or password.");
}
}
}

12. COLLECTION FRAMEWORK


1. Write a program to demonstrate the use of `ArrayList` and `LinkedList` for storing and
retrieving elements.

import [Link];
import [Link];
import [Link];

public class ListExample {


public static void main(String[] args) {
// Using ArrayList
List<String> arrayList = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");

[Link]("ArrayList Elements:");
for (String element : arrayList) {
[Link](element);
}

// Using LinkedList
List<String> linkedList = new LinkedList<>();
[Link]("Dog");
[Link]("Elephant");
[Link]("Frog");

[Link]("\nLinkedList Elements:");
for (String element : linkedList) {
[Link](element);
}
}
}

2. Create a program to use `HashMap` to store key-value pairs and demonstrate operations like
adding, removing, and searching for elements.
import [Link];

public class HashMapExample {


public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> hashMap = new HashMap<>();

// Adding elements to the HashMap


[Link](1, "Apple");
[Link](2, "Banana");
[Link](3, "Cherry");

// Display the HashMap


[Link]("HashMap Elements: " + hashMap);

// Removing an element from the HashMap


[Link](2);
[Link]("After removing key 2: " + hashMap);

// Searching for an element in the HashMap


if ([Link](1)) {
[Link]("HashMap contains key 1: " + [Link](1));
} else {
[Link]("HashMap does not contain key 1");
}

// Iterating over the HashMap


[Link]("Iterating over HashMap:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]("Key: " + [Link]() + ", Value: " + [Link]());
}
}
}

3. Develop a program to implement a stack and queue using collections.

// Stack Implementation

import [Link];

public class StackExample {


public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();

// Pushing elements onto the stack


[Link](10);
[Link](20);
[Link](30);

[Link]("Stack after pushes: " + stack);

// Popping elements from the stack


[Link]("Popped element: " + [Link]());
[Link]("Stack after pop: " + stack);

// Peeking the top element


[Link]("Top element: " + [Link]());

// Checking if the stack is empty


[Link]("Is stack empty? " + [Link]());
}
}

//queue implementation
import [Link];
import [Link];

public class QueueExample {


public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();

// Adding elements to the queue


[Link](10);
[Link](20);
[Link](30);

[Link]("Queue after additions: " + queue);

// Removing elements from the queue


[Link]("Removed element: " + [Link]());
[Link]("Queue after removal: " + queue);

// Peeking the front element


[Link]("Front element: " + [Link]());

// Checking if the queue is empty


[Link]("Is queue empty? " + [Link]());
}
}

13. JDBC
1. Write a program to connect to a database and execute a simple SQL query to retrieve data.

import [Link];
import [Link];
import [Link];
import [Link];

public class DatabaseConnectionExample {


public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String user = "yourUsername";
String password = "yourPassword";
// SQL query to execute
String query = "SELECT * FROM yourTableName";

try {
// Load the MySQL JDBC driver
[Link]("[Link]");

// Establish the connection


Connection connection = [Link](url, user, password);

// Create a statement
Statement statement = [Link]();

// Execute the query


ResultSet resultSet = [Link](query);

// Process the result set


while ([Link]()) {
[Link]("ID: " + [Link]("id"));
[Link]("Name: " + [Link]("name"));
[Link]("Age: " + [Link]("age"));
[Link]("-----");
}

// Close the resources


[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

2. Create a program to insert, update, and delete records in a database using JDBC.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JdbcExample {


public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String user = "yourUsername";
String password = "yourPassword";

try {
// Load the MySQL JDBC driver
[Link]("[Link]");

// Establish the connection


Connection connection = [Link](url, user, password);

// Insert a record
String insertSQL = "INSERT INTO yourTableName (id, name, age) VALUES (?, ?, ?)";
PreparedStatement insertStmt = [Link](insertSQL);
[Link](1, 1);
[Link](2, "Alice");
[Link](3, 30);
[Link]();
[Link]("Record inserted successfully!");

// Update a record
String updateSQL = "UPDATE yourTableName SET name = ?, age = ? WHERE id = ?";
PreparedStatement updateStmt = [Link](updateSQL);
[Link](1, "Alice Updated");
[Link](2, 31);
[Link](3, 1);
[Link]();
[Link]("Record updated successfully!");

// Delete a record
String deleteSQL = "DELETE FROM yourTableName WHERE id = ?";
PreparedStatement deleteStmt = [Link](deleteSQL);
[Link](1, 1);
[Link]();
[Link]("Record deleted successfully!");

// Close the resources


[Link]();
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}

3. Develop a program to execute a stored procedure using JDBC.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class StoredProcedureExample {


public static void main(String[] args) {
// Database credentials
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String user = "yourUsername";
String password = "yourPassword";

// SQL call to the stored procedure


String sql = "{CALL getEmployeeDetails(?)}";

try {
// Load the MySQL JDBC driver
[Link]("[Link]");

// Establish the connection


Connection connection = [Link](url, user, password);

// Create a CallableStatement to execute the stored procedure


CallableStatement callableStatement = [Link](sql);

// Set the input parameter


[Link](1, 1); // Assuming we want details of employee with ID 1

// Execute the stored procedure


ResultSet resultSet = [Link]();

// Process the result set


while ([Link]()) {
[Link]("ID: " + [Link]("id"));
[Link]("Name: " + [Link]("name"));
[Link]("Position: " + [Link]("position"));
[Link]("Salary: " + [Link]("salary"));
[Link]("-----");
}

// Close the resources


[Link]();
[Link]();
[Link]();
} catch (ClassNotFoundException | SQLException e) {
[Link]();
}
}
}

You might also like