sonakshi java file
sonakshi java file
SURAJMAL INSTITUTE
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.
SOURCE CODE:
// 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:
// 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:
System.out.println("Prime numbers between " + startRange + " and " + endRange + " are:");
for (int i = startRange; i <= endRange; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
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;
// Input
System.out.println("Enter dimensions of the rectangle:");
rectangle.input();
// Output
System.out.println("\nRectangle details:");
rectangle.output();
}
}
OUTPUT:
Q 5 - Write a program to remove duplicates from sorted array.
SOURCE CODE:
OUTPUT:
Q 6 - WAP to calculate first n Fibonacci numbers and store in an array.
SOURCE CODE:
import java.util.Scanner;
OUTPUT:
Q 7 -WAP to demonstrate use of method overloading to calculate area of square, rectangle and
triangle.
SOURCE CODE:
OUTPUT:
Q 8 -WAP that makes use of String class methods.
SOURCE CODE:
// 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);
// 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);
// 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:
// 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 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:
// Static block
static {
System.out.println("Static block executed.");
staticVar = 10;
}
// Static method
static void staticMethod() {
System.out.println("Static method called.");
}
OUTPUT:
Q 11 -WAP to demonstrate concept of ``this``.
SOURCE CODE:
// Constructor
public Person(String name, int age) {
// Using this keyword to differentiate between instance variable and constructor parameter
this.name = name;
this.age = age;
}
SOURCE CODE:
// Base class
class Animal {
void eat() {
System.out.println("Animal is eating...");
}
}
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;
void eat() {
System.out.println("Animal is eating...");
}
}
void bark() {
System.out.println("Dog is barking...");
}
}
// 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");
}
}
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.");
}
}
// Constructor
Circle(double radius) {
this.radius = radius;
}
// Constructor
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
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
// Second interface
interface Human {
int legs = 2; // Common data member for Animal and Human interfaces
@Override
public void speak() {
System.out.println("Person is speaking like a human.");
}
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;
OUTPUT:
Q 18- Write a program to demonstrate unchecked exception.
SOURCE CODE:
OUTPUT:
Q 19 - WAP to demonstrate the concept of user defined exceptions.
SOURCE CODE:
// 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;
}
System.out.println();
SOURCE CODE:
import java.util.Scanner;
OUTPUT:
Q 21-WAP to demonstrate creation of multiple child threads.
SOURCE CODE:
// Constructor
public MyThread(String threadName) {
this.threadName = threadName;
}
SOURCE CODE:
// 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;
SOURCE CODE:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
bos.write(studentData.getBytes());
bos.close();
fos.close();
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;
// 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 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;
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();
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;
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:
// Constructor
public SavingsAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
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:
@Override
public void run() {
System.out.println(message);
}
thread1.start();
thread2.start();
}
}
OUTPUT: