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

sonakshi java file

This document is a practical file for a Java programming course, detailing various programming assignments and their respective source codes. It includes tasks such as demonstrating primitive data types, arithmetic and bitwise operators, and implementing classes and methods for various functionalities. The file is submitted by a student named Sonakshi Sutradhar to Mr. Sandeep Kumar.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

sonakshi java file

This document is a practical file for a Java programming course, detailing various programming assignments and their respective source codes. It includes tasks such as demonstrating primitive data types, arithmetic and bitwise operators, and implementing classes and methods for various functionalities. The file is submitted by a student named Sonakshi Sutradhar to Mr. Sandeep Kumar.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

MAHARAJA

SURAJMAL INSTITUTE

JAVA PRACTICAL FILE


Course Code: BCA 104p
SUBMITTED TO: SUBMITTED BY:
MR. Sandeep Kumar Name: Sonakshi Sutradhar
Enrolment No.: 03014902024
Assistant Professor
Course: BCA (2nd Semester)
BCA Shift: Morning
Section: B
Index
S.No. Program Signature

1 WAP to print the size (in bytes) and range (smallest & largest) of all
primitive data types available in JAVA.
2 WAP to demonstrate the use of arithmetic and bitwise operators.
3 WAP to print all the prime numbers within a range (e.g. 1 to 100).
4 WAP declaring a class Rectangle with data member’s length and breadth
and member functions Input, Output and CalcArea.
5 Write a program to remove duplicates from sorted array.
6 WAP to calculate first n Fibonacci numbers and store in an array.
7 WAP to demonstrate use of method overloading to calculate area of square,
rectangle and triangle.
8 WAP that makes use of String class methods.
9 WAP that makes use of StringBuffer class methods.
10 WAP to demonstrate the use of static variable, static method and static
block.
11 WAP to demonstrate concept of ``this``.
12 WAP to demonstrate multi-level and hierarchical inheritance.
13 WAP to use super () to invoke base class constructor.
14 WAP to demonstrate run-time polymorphism.
15 WAP to implement abstract classes.
16 WAP to demonstrate the concept of interface when two interfaces have
unique methods and same data members.
17 WAP to demonstrate checked exception during file handling.
18 Write a program to demonstrate unchecked exception.
19 WAP to demonstrate the concept of user defined exceptions.
20 WAP to input salary of a person along with his name, if the salary is less
than 85,000 then throw an arithmetic exception with a proper message “not
eligible for loan”.
21 WAP to demonstrate creation of multiple child threads.
22 WAP that has two threads where one thread prints table of 5 and other
thread prints a string 10 times. Set and display the names and priorities of
these threads
23 WAP to create random access file and read & write integer data in it
24 WAP that writes student’s data (enrollment no, name, percentage, phone
no.) to a file and then reads the student data back from that file and display
it on the console. (Use BufferedInputStream and BufferedOuputStream).

25 WAP that accept two file names as command line arguments. Copy only
those lines from the first file to second file which contains the word
“Computers”. Also count number of words in first file.
26 WAP that take input from keyboard and write into a file using character
stream.
27 WAP to use Byte stream class to read from a text file and display the
content on the output screen.
28 WAP to use Byte stream class to read form a text file and copy the content
to another text file.

Application Based Practicals


1 Create a class employee which have name, age and address of
employee, include methods getdata() and showdata(), getdata() takes
the input from the user, showdata() display the data in following
format:
Name:
Age:
Address:
2 WAP to perform basic Calculator operations. Make a menu driven
program to select operation to perform (+ - * / ). Take 2 integers and
perform operation as chosen by user.
3 WAP to make use of BufferedStream to read lines from the keyboard
until 'STOP' is typed.
4 WAP declaring a Java class called SavingsAccount with members
``accountNumber`` and ``Balance``. Provide member functions as
``depositAmount ()`` and ``withdrawAmount ()``. If user tries to
withdraw an amount greater than their balance then throw a user-
defined exception.
5 WAP creating 2 threads using Runnable interface. Print your name in
``run ()`` method of first class and "Hello Java" in ``run ()`` method of
second thread.
Q 1-WAP to print the size (in bytes) and range (smallest & largest) of all primitive data types available
in JAVA.

SOURCE CODE:

public class PrimitiveDataTypes {


public static void main(String[] args) {
System.out.println("Primitive Data Types in Java:");
System.out.println("-----------------------------------");

// byte
System.out.println("byte:");
System.out.println("Size: " + Byte.SIZE / 8 + " bytes");
System.out.println("Range: from " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
System.out.println();

// short
System.out.println("short:");
System.out.println("Size: " + Short.SIZE / 8 + " bytes");
System.out.println("Range: from " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.println();

// int
System.out.println("int:");
System.out.println("Size: " + Integer.SIZE / 8 + " bytes");
System.out.println("Range: from " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.println();

// long
System.out.println("long:");
System.out.println("Size: " + Long.SIZE / 8 + " bytes");
System.out.println("Range: from " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);
System.out.println();

// float
System.out.println("float:");
System.out.println("Size: " + Float.SIZE / 8 + " bytes");
System.out.println("Range: from " + -Float.MAX_VALUE + " to " + Float.MAX_VALUE);
System.out.println();

// double
System.out.println("double:");
System.out.println("Size: " + Double.SIZE / 8 + " bytes");
System.out.println("Range: from " + -Double.MAX_VALUE + " to " + Double.MAX_VALUE);
System.out.println();

// char
System.out.println("char:");
System.out.println("Size: " + Character.SIZE / 8 + " bytes");
System.out.println("Range: from '\\u0000' to '\\uffff'");
System.out.println();
}
}
OUTPUT:
Q 2-WAP to demonstrate the use of arithmetic and bitwise operators.

SOURCE CODE:

public class OperatorDemo {


public static void main(String[] args) {
// Arithmetic operators
int a = 10;
int b = 5;

// Addition
int sum = a + b;
System.out.println("Addition: " + sum);

// Subtraction
int difference = a - b;
System.out.println("Subtraction: " + difference);

// Multiplication
int product = a * b;
System.out.println("Multiplication: " + product);

// Division
int quotient = a / b;
System.out.println("Division: " + quotient);

// Modulus
int remainder = a % b;
System.out.println("Modulus: " + remainder);

// Bitwise operators
int x = 5; // Binary representation: 0101
int y = 3; // Binary representation: 0011

// Bitwise AND
int bitwiseAndResult = x & y; // Result: 0001 (1 in decimal)
System.out.println("Bitwise AND: " + bitwiseAndResult);

// Bitwise OR
int bitwiseOrResult = x | y; // Result: 0111 (7 in decimal)
System.out.println("Bitwise OR: " + bitwiseOrResult);

// Bitwise XOR
int bitwiseXorResult = x ^ y; // Result: 0110 (6 in decimal)
System.out.println("Bitwise XOR: " + bitwiseXorResult);

// Bitwise NOT
int bitwiseNotResultX = ~x; // Result: 1111 1111 1111 1010 (-6 in decimal due to two's complement)
System.out.println("Bitwise NOT of x: " + bitwiseNotResultX);

int bitwiseNotResultY = ~y; // Result: 1111 1111 1111 1100 (-4 in decimal due to two's complement)
System.out.println("Bitwise NOT of y: " + bitwiseNotResultY);

// Left shift
int leftShiftResult = x << 1; // Result: 1010 (10 in decimal)
System.out.println("Left shift of x by 1: " + leftShiftResult);

// Right shift
int rightShiftResult = y >> 1; // Result: 0001 (1 in decimal)
System.out.println("Right shift of y by 1: " + rightShiftResult);
}
}

OUTPUT:
Q 3 -WAP to print all the prime numbers within a range (e.g. 1 to 100).

SOURCE CODE:

public class PrimeNumbersInRange {


public static void main(String[] args) {
int startRange = 1;
int endRange = 100;

System.out.println("Prime numbers between " + startRange + " and " + endRange + " are:");
for (int i = startRange; i <= endRange; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

// Function to check if a number is prime


public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
if (num <= 3) {
return true;
}
if (num % 2 == 0 || num % 3 == 0) {
return false;
}
for (int i = 5; i * i <= num; i = i + 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
}

OUTPUT:
Q 4-WAP declaring a class Rectangle with data member’s length and breadth and member functions
Input, Output and CalcArea.

SOURCE CODE:

import java.util.Scanner;

public class Rectangle {


// Data members
private double length;
private double breadth;

// Member function to input length and breadth


public void input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length: ");
length = scanner.nextDouble();
System.out.print("Enter breadth: ");
breadth = scanner.nextDouble();
}

// Member function to output length and breadth


public void output() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
}

// Member function to calculate area


public double calcArea() {
return length * breadth;
}

public static void main(String[] args) {


Rectangle rectangle = new Rectangle();

// Input
System.out.println("Enter dimensions of the rectangle:");
rectangle.input();

// Output
System.out.println("\nRectangle details:");
rectangle.output();

// Calculate and print area


double area = rectangle.calcArea();
System.out.println("Area: " + area);

}
}
OUTPUT:
Q 5 - Write a program to remove duplicates from sorted array.

SOURCE CODE:

public class RemoveDuplicatesFromSortedArray {


public static void main(String[] args) {
int[] sortedArray = {1, 1, 2, 2, 3, 4, 4, 5, 5, 5, 6};

int length = removeDuplicates(sortedArray);

System.out.println("Array after removing duplicates:");


for (int i = 0; i < length; i++) {
System.out.print(sortedArray[i] + " ");
}
}

public static int removeDuplicates(int[] nums) {


if (nums.length == 0) {
return 0;
}
int index = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}

OUTPUT:
Q 6 - WAP to calculate first n Fibonacci numbers and store in an array.

SOURCE CODE:

import java.util.Scanner;

public class FibonacciNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();

long[] fibonacciArray = new long[n];

// Calculate and store Fibonacci numbers


for (int i = 0; i < n; i++) {
if (i <= 1) {
fibonacciArray[i] = i;
} else {
fibonacciArray[i] = fibonacciArray[i - 1] + fibonacciArray[i - 2];
}
}

// Print Fibonacci numbers


System.out.println("First " + n + " Fibonacci numbers:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacciArray[i] + " ");
}
}
}

OUTPUT:
Q 7 -WAP to demonstrate use of method overloading to calculate area of square, rectangle and
triangle.

SOURCE CODE:

public class AreaCalculator {


// Method to calculate area of a square
public static double calculateArea(double side) {
return side * side;
}

// Method to calculate area of a rectangle


public static double calculateArea(double length, double breadth) {
return length * breadth;
}

// Method to calculate area of a triangle


public static double calculateArea(double base, double height, String shape) {
if (shape.equalsIgnoreCase("triangle")) {
return 0.5 * base * height;
} else {
System.out.println("Invalid shape. Please provide 'triangle'.");
return -1;
}
}

public static void main(String[] args) {


// Calculate area of a square
double squareArea = calculateArea(5);
System.out.println("Area of square with side 5: " + squareArea);

// Calculate area of a rectangle


double rectangleArea = calculateArea(4, 6);
System.out.println("Area of rectangle with length 4 and breadth 6: " + rectangleArea);

// Calculate area of a triangle


double triangleArea = calculateArea(3, 4, "triangle");
System.out.println("Area of triangle with base 3 and height 4: " + triangleArea);
}
}

OUTPUT:
Q 8 -WAP that makes use of String class methods.

SOURCE CODE:

public class StringMethodsDemo {


public static void main(String[] args) {
String str = "Hello, World!";

// Length
int length = str.length();
System.out.println("Length of the string: " + length);

// Character at index
char charAtIndex = str.charAt(7);
System.out.println("Character at index 7: " + charAtIndex);

// Substring
String substring = str.substring(7);
System.out.println("Substring from index 7: " + substring);

// Substring with start and end index


String substringRange = str.substring(7, 12);
System.out.println("Substring from index 7 to 11: " + substringRange);

// Concatenation
String newStr = str.concat(" How are you?");
System.out.println("Concatenated string: " + newStr);

// Replace
String replacedStr = str.replace("World", "Universe");
System.out.println("String after replacement: " + replacedStr);

// Index of
int indexOfComma = str.indexOf(',');
System.out.println("Index of comma: " + indexOfComma);

// Conversion to uppercase
String upperCaseStr = str.toUpperCase();
System.out.println("Uppercase string: " + upperCaseStr);

// Conversion to lowercase
String lowerCaseStr = str.toLowerCase();
System.out.println("Lowercase string: " + lowerCaseStr);

// Trim
String strWithWhitespace = " Hello, World! ";
String trimmedStr = strWithWhitespace.trim();
System.out.println("Trimmed string: " + trimmedStr);

// Check if starts with


boolean startsWithHello = str.startsWith("Hello");
System.out.println("Starts with 'Hello': " + startsWithHello);

// Check if ends with


boolean endsWithExclamation = str.endsWith("!");
System.out.println("Ends with '!': " + endsWithExclamation);

// Split
String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split(" ");
System.out.println("Words in the sentence:");
for (String word : words) {
System.out.println(word);
}
}
}

OUTPUT:
Q 9 -WAP that makes use of StringBuffer class methods.

SOURCE CODE:

public class StringBufferMethodsDemo {


public static void main(String[] args) {
// Create a StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello");

// Append
stringBuffer.append(" World");
System.out.println("After append: " + stringBuffer);

// Insert
stringBuffer.insert(5, ", ");
System.out.println("After insert: " + stringBuffer);

// Replace
stringBuffer.replace(6, 11, "Universe");
System.out.println("After replace: " + stringBuffer);

// Delete
stringBuffer.delete(5, 15);
System.out.println("After delete: " + stringBuffer);

// Reverse
stringBuffer.reverse();
System.out.println("After reverse: " + stringBuffer);

// Length
int length = stringBuffer.length();
System.out.println("Length of StringBuffer: " + length);

// Capacity
int capacity = stringBuffer.capacity();
System.out.println("Capacity of StringBuffer: " + capacity);

// Set length
stringBuffer.setLength(5);
System.out.println("After setting length: " + stringBuffer);

// Get character at index


char charAtIndex = stringBuffer.charAt(2);
System.out.println("Character at index 2: " + charAtIndex);

// Get substring
String substring = stringBuffer.substring(1, 3);
System.out.println("Substring from index 1 to 2: " + substring);

// Clear
stringBuffer.delete(0, stringBuffer.length());
System.out.println("After clearing: " + stringBuffer);
}
}
OUTPUT:
Q 10 -WAP to demonstrate the use of static variable, static method and static block.

SOURCE CODE:

public class StaticDemo {


// Static variable
static int staticVar;

// Static block
static {
System.out.println("Static block executed.");
staticVar = 10;
}

// Static method
static void staticMethod() {
System.out.println("Static method called.");
}

public static void main(String[] args) {


// Accessing static variable and method
System.out.println("Value of staticVar: " + staticVar);
staticMethod();
}
}

OUTPUT:
Q 11 -WAP to demonstrate concept of ``this``.

SOURCE CODE:

public class Person {


// Instance variables
String name;
int age;

// Constructor
public Person(String name, int age) {
// Using this keyword to differentiate between instance variable and constructor parameter
this.name = name;
this.age = age;
}

// Method to display information about the person


public void displayInfo() {
// Using this keyword to refer to instance variables within the method
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}

// Method to compare two Person objects


public boolean isSamePerson(Person otherPerson) {
// Using this keyword to refer to instance variables of the current object
if (this.name.equals(otherPerson.name) && this.age == otherPerson.age) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// Creating Person objects
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);

// Display information about person1


System.out.println("Information about person1:");
person1.displayInfo();

// Display information about person2


System.out.println("\nInformation about person2:");
person2.displayInfo();

// Compare person1 with person2


System.out.println("\nAre person1 and person2 the same?");
boolean samePerson = person1.isSamePerson(person2);
if (samePerson) {
System.out.println("Yes, they are the same person.");
} else {
System.out.println("No, they are different people.");
}
}
OUTPUT:
Q 12 -WAP to demonstrate multi-level and hierarchical inheritance.

SOURCE CODE:

// Base class
class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}

// Derived class (inherits from Animal)


class Dog extends Animal {
void bark() {
System.out.println("Dog is barking...");
}
}

// Derived class (inherits from Animal)


class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing...");
}
}

// Multi-level inheritance: Derived class (inherits from Dog)


class Labrador extends Dog {
void color() {
System.out.println("Labrador is golden in color...");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
// Multi-level inheritance
Labrador labrador = new Labrador();
labrador.eat(); // inherited from Animal
labrador.bark(); // inherited from Dog
labrador.color(); // inherited from Labrador

System.out.println();

// Hierarchical inheritance
Cat cat = new Cat();
cat.eat(); // inherited from Animal
cat.meow(); // inherited from Cat

}
}
OUTPUT:
Q 13 -WAP to use super () to invoke base class constructor.

SOURCE CODE:

// Base class
class Animal {
String species;

// Base class constructor


Animal(String species) {
this.species = species;
System.out.println("Animal constructor called with species: " + species);
}

void eat() {
System.out.println("Animal is eating...");
}
}

// Derived class (inherits from Animal)


class Dog extends Animal {
String breed;

// Derived class constructor


Dog(String species, String breed) {
super(species); // Calling base class constructor using super()
this.breed = breed;
System.out.println("Dog constructor called with breed: " + breed);
}

void bark() {
System.out.println("Dog is barking...");
}
}

public class SuperConstructorDemo {


public static void main(String[] args) {
// Creating Dog object
Dog dog = new Dog("Canine", "Labrador");

// Calling methods
dog.eat(); // Inherited from Animal class
dog.bark(); // Defined in Dog class
}
}

OUTPUT:
Q 14 - WAP to demonstrate run-time polymorphism.

SOURCE CODE:

// Base class
class Animal {
// Method to make sound
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Derived class (inherits from Animal)


class Dog extends Animal {
// Overriding makeSound method
@Override
void makeSound() {
System.out.println("Dog barks");
}
}

// Derived class (inherits from Animal)


class Cat extends Animal {
// Overriding makeSound method
@Override
void makeSound() {
System.out.println("Cat meows");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
// Creating Animal references
Animal animal1 = new Dog(); // Dog object assigned to Animal reference
Animal animal2 = new Cat(); // Cat object assigned to Animal reference

// Calling makeSound method


animal1.makeSound(); // Calls Dog's makeSound method
animal2.makeSound(); // Calls Cat's makeSound method
}
}

OUTPUT:
Q 15 - WAP to implement abstract classes.

SOURCE CODE:

// Abstract class
abstract class Shape {
// Abstract method
abstract double area();

// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

// Concrete subclass (inherits from Shape)


class Circle extends Shape {
double radius;

// Constructor
Circle(double radius) {
this.radius = radius;
}

// Implementing abstract method area() for Circle


@Override
double area() {
return Math.PI * radius * radius;
}
}

// Concrete subclass (inherits from Shape)


class Rectangle extends Shape {
double length;
double width;

// Constructor
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Implementing abstract method area() for Rectangle


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

public class AbstractClassDemo {


public static void main(String[] args) {
// Creating objects of Circle and Rectangle
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
// Calling area() method on Circle and Rectangle objects
System.out.println("Area of circle: " + circle.area());
System.out.println("Area of rectangle: " + rectangle.area());

// Calling display() method on Circle and Rectangle objects


circle.display();
rectangle.display();
}
}

OUTPUT:
Q 16 -WAP to demonstrate the concept of interface when two interfaces have unique methods and
same data members.

SOURCE CODE:

// First interface
interface Animal {
int legs = 4; // Common data member for Animal and Human interfaces

void eat(); // Unique method for Animal interface


}

// Second interface
interface Human {
int legs = 2; // Common data member for Animal and Human interfaces

void speak(); // Unique method for Human interface


}

// Concrete class implementing both interfaces


class Person implements Animal, Human {
@Override
public void eat() {
System.out.println("Person is eating like an animal.");
}

@Override
public void speak() {
System.out.println("Person is speaking like a human.");
}

// Accessing common data member from both interfaces


void displayLegs() {
System.out.println("Number of legs: " + Animal.legs); // Accessing Animal interface's legs
System.out.println("Number of legs: " + Human.legs); // Accessing Human interface's legs
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Person person = new Person();
person.eat(); // Calling unique method from Animal interface
person.speak(); // Calling unique method from Human interface
person.displayLegs(); // Calling method to display number of legs
}
}

OUTPUT:
Q 17-WAP to demonstrate checked exception during file handling.

SOURCE CODE:

import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileHandlingDemo {


public static void main(String[] args) {
// Attempt to read a file that does not exist
try {
File file = new File("nonexistent.txt");
FileReader fr = new FileReader(file); // This line can throw FileNotFoundException
fr.close();
} catch (FileNotFoundException e) {
// Handle FileNotFoundException
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
// Handle IOException
System.out.println("IOException occurred: " + e.getMessage());
}
}
}

OUTPUT:
Q 18- Write a program to demonstrate unchecked exception.

SOURCE CODE:

public class UncheckedExceptionDemo {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

// Attempt to access an element outside the bounds of the array


try {
// Accessing the 6th element, which does not exist
int sixthElement = numbers[5]; // This line can throw ArrayIndexOutOfBoundsException
System.out.println("Sixth element: " + sixthElement);
} catch (ArrayIndexOutOfBoundsException e) {
// Handle ArrayIndexOutOfBoundsException
System.out.println("Array index out of bounds: " + e.getMessage());
}

// Attempt to perform arithmetic division by zero


try {
int result = 10 / 0; // This line can throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handle ArithmeticException
System.out.println("Arithmetic exception: " + e.getMessage());
}
}
}

OUTPUT:
Q 19 - WAP to demonstrate the concept of user defined exceptions.

SOURCE CODE:

// Custom exception class


class InvalidAgeException extends Exception {
// Constructor with message
public InvalidAgeException(String message) {
super(message);
}
}

// Class representing a person


class Person {
// Instance variable
private String name;
private int age;

// Constructor
public Person(String name, int age) throws InvalidAgeException {
// Validate age
if (age < 0 || age > 150) {
// Throw custom exception if age is invalid
throw new InvalidAgeException("Invalid age: " + age);
}
this.name = name;
this.age = age;
}

// Method to display person's details


public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class UserDefinedExceptionDemo {


public static void main(String[] args) {
try {
// Create a person object with valid age
Person person1 = new Person("Alice", 30);
person1.displayDetails();

System.out.println();

// Create a person object with invalid age


Person person2 = new Person("Bob", 200); // This line can throw InvalidAgeException
person2.displayDetails(); // This line won't execute if an exception is thrown
} catch (InvalidAgeException e) {
// Handle the custom exception
System.out.println("Exception caught: " + e.getMessage());
}
}
}
OUTPUT:
Q 20 - WAP to input salary of a person along with his name, if the salary is less than 85,000 then throw
an arithmetic exception with a proper message “not eligible for loan”.

SOURCE CODE:

import java.util.Scanner;

public class LoanEligibility {


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

// Input name and salary


System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your salary: ");
double salary = scanner.nextDouble();

// Check if salary is less than 85,000


try {
if (salary < 85000) {
throw new ArithmeticException("Not eligible for loan");
} else {
System.out.println("Congratulations, " + name + "! You are eligible for a loan.");
}
} catch (ArithmeticException e) {
// Handle the exception
System.out.println(e.getMessage());
}
}
}

OUTPUT:
Q 21-WAP to demonstrate creation of multiple child threads.

SOURCE CODE:

// Child thread class implementing Runnable interface


class MyThread implements Runnable {
// Thread name
private String threadName;

// Constructor
public MyThread(String threadName) {
this.threadName = threadName;
}

// Run method (entry point for the thread)


public void run() {
System.out.println("Thread '" + threadName + "' is running.");
try {
// Simulate some task
for (int i = 1; i <= 5; i++) {
System.out.println("Thread '" + threadName + "' executing task " + i);
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println("Thread '" + threadName + "' interrupted.");
}
System.out.println("Thread '" + threadName + "' exiting.");
}
}

public class MultipleThreadDemo {


public static void main(String[] args) {
System.out.println("Main thread starting.");

// Create multiple threads


Thread thread1 = new Thread(new MyThread("Thread 1"));
Thread thread2 = new Thread(new MyThread("Thread 2"));
Thread thread3 = new Thread(new MyThread("Thread 3"));

// Start the threads


thread1.start();
thread2.start();
thread3.start();

// Displaying main thread's name


System.out.println("Main thread exiting.");
}
}
OUTPUT:
Q 22- WAP that has two threads where one thread prints table of 5 and other thread prints a string 10
times. Set and display the names and priorities of these threads

SOURCE CODE:

class TablePrinter extends Thread {


@Override
public void run() {
System.out.println("Thread '" + getName() + "' is running with priority " + getPriority() + ".");
for (int i = 1; i <= 10; i++) {
System.out.println("5 * " + i + " = " + (5 * i));
}
}
}

class StringPrinter extends Thread {


@Override
public void run() {
System.out.println("Thread '" + getName() + "' is running with priority " + getPriority() + ".");
for (int i = 1; i <= 10; i++) {
System.out.println("Printed by thread '" + getName() + "': Hello, world! (" + i + ")");
}
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
// Creating and setting priority for TablePrinter thread
TablePrinter tablePrinter = new TablePrinter();
tablePrinter.setName("TablePrinterThread");
tablePrinter.setPriority(Thread.MAX_PRIORITY);

// Creating and setting priority for StringPrinter thread


StringPrinter stringPrinter = new StringPrinter();
stringPrinter.setName("StringPrinterThread");
stringPrinter.setPriority(Thread.MIN_PRIORITY);

// Starting threads
tablePrinter.start();
stringPrinter.start();
}
}
OUTPUT:
Q 23-WAP to create random access file and read & write integer data in it

SOURCE CODE:

import java.io.RandomAccessFile;
import java.io.IOException;

public class RandomAccessFileDemo {


public static void main(String[] args) {
// Define file name
String fileName = "random_access_file.dat";

// Write integer data to the file


writeIntegersToFile(fileName);

// Read and display integer data from the file


readIntegersFromFile(fileName);
}

// Method to write integer data to the file


private static void writeIntegersToFile(String fileName) {
try (RandomAccessFile file = new RandomAccessFile(fileName, "rw")) {
// Write integer data to the file
file.writeInt(10);
file.writeInt(20);
file.writeInt(30);
file.writeInt(40);
file.writeInt(50);
System.out.println("Integer data has been written to the file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
}
}

// Method to read and display integer data from the file


private static void readIntegersFromFile(String fileName) {
try (RandomAccessFile file = new RandomAccessFile(fileName, "r")) {
System.out.println("Reading integer data from the file:");
while (file.getFilePointer() < file.length()) {
int data = file.readInt();
System.out.println(data);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the file: " + e.getMessage());
}
}
}
OUTPUT:
Q -24 - WAP that writes student’s data (enrollment no, name, percentage, phone no.) to a file and then
reads the student data back from that file and display it on the console. (Use BufferedInputStream
and BufferedOuputStream).

SOURCE CODE:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class StudentDataFileDemo {


public static void main(String[] args) {
String enrollmentNo = "ENR02414902024";
String name = "Meenu Mishra";
String percentage = "98.5";
String phoneNo = "9876543210";

String studentData = enrollmentNo + "," + name + "," + percentage + "," + phoneNo;

// Writing student data to file


try {
FileOutputStream fos = new FileOutputStream("student.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);

bos.write(studentData.getBytes());
bos.close();
fos.close();

System.out.println("Student data written to file successfully.\n");


} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}

// Reading student data from file


try {
FileInputStream fis = new FileInputStream("student.txt");
BufferedInputStream bis = new BufferedInputStream(fis);

int i;
System.out.println("Reading student data from file:");
while ((i = bis.read()) != -1) {
System.out.print((char) i);
}
bis.close();
fis.close();
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
}
}
}
OUTPUT:
Q 25-WAP that accept two file names as command line arguments. Copy only those lines from the first
file to second file which contains the
word “Computers”. Also count number of words in first file.

SOURCE CODE:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyLinesContainingWord {


public static void main(String[] args) {
// Check if two file names are provided as command-line arguments
if (args.length != 2) {
System.out.println("Usage: java CopyLinesContainingWord <inputFile> <outputFile>");
return;
}

String inputFile = args[0];


String outputFile = args[1];

// Count number of words in the first file


int wordCount = countWords(inputFile);
System.out.println("Number of words in the first file: " + wordCount);

// Copy lines containing the word "Computers" from the first file to the second file
copyLinesContainingWord(inputFile, outputFile);
System.out.println("Lines containing the word 'Computers' copied to the second file.");
}

// Method to count the number of words in a file


private static int countWords(String fileName) {
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
// Split the line into words using space as delimiter
String[] words = line.split("\\s+");
wordCount += words.length;
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
return wordCount;
}

// Method to copy lines containing the word "Computers" from one file to another
private static void copyLinesContainingWord(String inputFile, String outputFile) {
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
// Check if the line contains the word "Computers"
if (line.contains("Computers")) {
// Write the line to the output file
writer.write(line);
writer.newLine(); // Add a new line after each line
}
}
} catch (IOException e) {
System.out.println("An error occurred while copying lines: " + e.getMessage());
}
}
}

OUTPUT:
Q 26 - WAP that take input from keyboard and write into a file using
character stream.

SOURCE CODE:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class GFG {
public static void main(String[] args)
throws IOException{
String text
= "Welcome\nHappy Learning!";
Path fileName = Path.of(
"/Users/mayanksolanki/Desktop/demo.docx");
Files.writeString(fileName, text);
String file_content = Files.readString(fileName);
System.out.println(file_content);
}
}

OUTPUT:
Q 27-WAP to use Byte stream class to read from a text file and display the
content on the output screen.

SOURCE CODE:
import java.io.FileOutputStream;
import java.io.IOException;
class GFG{
public static void main(String args[]) {
try {
FileOutputStream fout= new FileOutputStream("demo.txt");
String s= "Welcome! This is an example of Java program to write Bytes using ByteStream.";
byte b[] = s.getBytes();
fout.write(b);
fout.close();
}
catch (IOException e) {
// Display and print the exception
System.out.println(e);
}
}
}

OUTPUT:
Q 28 -WAP to use Byte stream class to read form a text file and copy the
content to another text file.

SOURCE CODE:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class GFG {
public static void main(String[] args){
Try{
FileReader fr = new FileReader("gfgInput.txt");
FileWriter fw = new FileWriter("gfgOutput.txt");
String str = "";
int i;
while ((i = fr.read()) != -1) {
str += (char)i;
}
System.out.println(str);
fw.write(str);
fr.close();
fw.close();
System.out.println(
"File reading and writing both done");
}
catch (IOException e) {
System.out.println(
"There are some IOException");
}
}
}

OUTPUT:
Q 1 - Create a class employee which have name, age and address of employee, include methods
getdata() and showdata(), getdata() takes the input from the user, showdata() display the data in
following format:
Name: Age: Address:

SOURCE CODE :
import java.util.Scanner;

public class Employee {


private String name;
private int age;
private String address;

// Method to get data from the user


public void getData() {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter name: ");


name = scanner.nextLine();

System.out.print("Enter age: ");


age = scanner.nextInt();
scanner.nextLine(); // Consume newline character left by nextInt()

System.out.print("Enter address: ");


address = scanner.nextLine();
}

// Method to display employee data


public void showData() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}

// Main method for testing the class


public static void main(String[] args) {
Employee emp = new Employee();

// Get data from the user


emp.getData();

// Display employee data


System.out.println("\nEmployee Details:");
emp.showData();
}
}
OUTPUT:
Q 2 - WAP to perform basic Calculator operations. Make a menu driven
program to select operation to perform (+ - * / ). Take 2 integers and perform operation as chosen by
user.

SOURCE CODE :
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt user to enter two numbers
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();

System.out.print("Enter second number: ");


double num2 = scanner.nextDouble();
// Display menu options
System.out.println("Select operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");

// Prompt user to select an operation


System.out.print("Enter choice (1-4): ");
int choice = scanner.nextInt();
double result = 0;
switch (choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero!");
return;
}
break;
default:
System.out.println("Invalid choice!");
return;
}
// Display the result
System.out.println("Result: " + result);

scanner.close();
}
}
OUTPUT:
Q 3 - WAP to make use of BufferedStream to read lines from the keyboard
until 'STOP' is typed.

SOURCE CODE:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.I+OException;

public class BufferedStreamExample {


public static void main(String[] args) {
// Create BufferedReader object to read input from the keyboard
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

// Use try-with-resources to automatically close the BufferedReader


try {
System.out.println("Enter lines (type 'STOP' to end):");

String line;
// Read lines until 'STOP' is typed
while (!(line = reader.readLine()).equalsIgnoreCase("STOP")) {
System.out.println("You entered: " + line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading input: " + e.getMessage());
} finally {
// Close the BufferedReader
try {
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while closing the BufferedReader: " + e.getMessage());
}
}
}
}

OUTPUT:
Q 4 -WAP declaring a Java class called SavingsAccount with members
``accountNumber`` and ``Balance``. Provide member functions as
``depositAmount ()`` and ``withdrawAmount ()``. If user tries to withdraw an amount greater than
their balance then throw a user-defined exception

SOURCE CODE:

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {
super(message);
}
}

public class SavingsAccount {


private String accountNumber;
private double balance;

// Constructor
public SavingsAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}

// Method to deposit amount into the account


public void depositAmount(double amount) {
balance += amount;
System.out.println("Amount deposited successfully. Current balance: " + balance);
}

// Method to withdraw amount from the account


public void withdrawAmount(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance. Cannot withdraw amount.");
}
balance -= amount;
System.out.println("Amount withdrawn successfully. Current balance: " + balance);
}

// Main method for testing


public static void main(String[] args) {
SavingsAccount account = new SavingsAccount("S123456", 1000);

try {
account.depositAmount(500);
account.withdrawAmount(200);
account.withdrawAmount(1500); // This should throw InsufficientBalanceException
} catch (InsufficientBalanceException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT:
Q 5 - WAP creating 2 threads using Runnable interface. Print your name in
``run ()`` method of first class and "Hello Java" in ``run ()`` method of second thread.

SOURCE CODE:

public class ThreadExample implements Runnable {

private String message;

public ThreadExample(String message) {


this.message = message;
}

@Override
public void run() {
System.out.println(message);
}

public static void main(String[] args) {


Thread thread1 = new Thread(new ThreadExample("My Name"));
Thread thread2 = new Thread(new ThreadExample("Hello Java"));

thread1.start();
thread2.start();
}
}

OUTPUT:

You might also like