Java File
Java File
Code:
import java.util.Scanner;
// Constructor
public Account(String customerName, int accountNumber, double balance, String
accountType) {
this.customerName = customerName;
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
// Constructor
public SavingsAccount(String customerName, int accountNumber, double balance, double
interestRate) {
super(customerName, accountNumber, balance, "Savings");
this.interestRate = interestRate;
}
// Constructor
public CurrentAccount(String customerName, int accountNumber, double balance, double
minimumBalance, double penalty) {
super(customerName, accountNumber, balance, "Current");
this.minimumBalance = minimumBalance;
this.penalty = penalty;
}
// Display balances
System.out.println("\nSavings Account:");
savingsAccount.displayBalance();
System.out.println("\nCurrent Account:");
currentAccount.displayBalance();
scanner.close();
}
}
Output:
Code:
import java.util.Scanner;
class Publication {
String title; double
price; String
authorName;
ASHISH KUMAR
SINGH:
23FS20MCA00015:
Enter publication title:
Java Programming
Enter publication price:
50
Enter author's name:
John Doe
Enter page count:
300
Book details:
Title: Java Programming
Price: $50.0
Author's Name: John Doe
Page Count: 300
Ebook details:
Title: Introduction to Algorithms
Price: $40.0
Author's Name: Jane Smith
Playing Time: 120 minutes
Que 34: Assume that a shape interface contains the data members PI and
functions area () and perimeter (). Implement these two methods according to
type of shape like circle, rectangle and square classes.
Code: interface
Shape {
double PI = 3.14159; // Constant PI
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Implementing interface method to calculate area of circle
public double area() { return PI * radius * radius;
}
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Constructor public
Square(double side) {
this.side = side;
}
System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.area());
System.out.println("Perimeter: " + rectangle.perimeter());
System.out.println("\nSquare:");
OUTPUT
Que 35: Assume that binary interface contains the method: binary to decimal,
decimal to binary, two’s complement and binary addition. Create the
appropriate classes to implement these methods.
Code:
interface Binary {
// Method to convert binary to decimal
int binaryToDecimal(String binary);
return sum.toString();
}
void defaultMethod() {
System.out.println("This is a default method in Package 1");
}
package package2;
import package_1.PublicClass;
}
Output:
Que 37: Design a package to contain the class student and another package that
contains the interface sports. Write a program to display the Rollno, Paper1,
Paper2 and total score of the candidates.
Code:
// Package containing the Student class package
studentPackage;
OUTPUT
Que 38: Write a program to show the use of simple try/catch
statement.
Code:
public class LAB_38 {
public static void main(String[] args) {
System.out.println("Name :ASHISH");
System.out.println("Reg. No. : 23FS20MCA00015"); try {
// Code that may throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result); // This line won't be executed if an exception
occurs
} catch (ArithmeticException e) {
// Catch block to handle the exception
System.out.println("Exception caught: " + e.getMessage());
}
System.out.println("Name :ASHISH");
System.out.println("Reg. No. : 23FS20MCA00015"); try {
// Outer try block
System.out.println("Outer try block starts");
try {
// Inner try block
System.out.println("Inner try block starts");
System.out.println("Name :ASHISH");
System.out.println("Reg. No. : 23FS20MCA00015"); try
{
// Calling a method that throws an exception
readFromFile("nonexistentfile.txt");
} catch (IOException e) {
// Catching the exception thrown by readFromFile method
System.out.println("Exception caught: " + e.getMessage());
} finally {
// Finally block executes regardless of whether an exception occurred or not
System.out.println("Finally block executed");
}
}
Que41: Write a program to create a custom exception. Show its use with the
help o java program.
Code:
// Custom exception class class
CustomException extends Exception {
// Constructor public
CustomException(String message) {
super(message);
}
}
Que42: Write a program to read two integer number and calculate the division
of these two numbers, throw an exception when wrong type of data is keyed
in. and also maintain a try block to detect and throw exception if condition
“divide by zero” occurs.
Code: import
java.util.Scanner;
// Custom exception class for invalid input data class
InvalidInputException extends Exception { public
InvalidInputException(String message) {
super(message);
}
}
public class LAB_42 {
public static void main(String[] args) {
System.out.println("Name :ASHISH ");
System.out.println("Reg. No. : 23FS20MCA00015");
Scanner scanner = new Scanner(System.in);
try
{
// Read two integer numbers
System.out.print("Enter first number: ");
int num1 = readInteger(scanner);
// Perform division
int result = divide(num1, num2);
System.out.println("Result of division: " + result);
} catch (InvalidInputException e) {
// Catch block for invalid input data
System.out.println("Invalid input: " + e.getMessage());
} catch (ArithmeticException e) {
// Catch block for division by zero
System.out.println("Division by zero: " + e.getMessage());
} finally {
// Close the scanner
scanner.close();
}
}
// Method to read integer input from the user public static int
readInteger(Scanner scanner) throws InvalidInputException { if
(scanner.hasNextInt()) { return scanner.nextInt();
} else { throw new InvalidInputException("Input is not
an integer");
}
}
Output:
// Close streams
bufferedReader.close();
bufferedWriter.close();
try {
// Create FileOutputStream object
FileOutputStream outputStream = new FileOutputStream(filePath);
// File path
String filePath = "output.txt";
try {
// Create FileInputStream object
FileInputStream inputStream = new FileInputStream(filePath);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Que47: Write a program to create a sequential file that could store details of
five students. Details include id, name, class, semester, three subject marks.
Compute and print students information and their total marks.
Code:
import java.io.*;
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Method to read student details from file, compute total marks, and print information
public static void readFromFile(String filePath) {
try (FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String currentLine;
while ((currentLine = bufferedReader.readLine()) != null) {
String[] details = currentLine.split(",");
int id = Integer.parseInt(details[0]);
String name = details[1];
int classNo = Integer.parseInt(details[2]);
String semester = details[3];
int marks1 = Integer.parseInt(details[4]);
int marks2 = Integer.parseInt(details[5]);
int marks3 = Integer.parseInt(details[6]);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Error parsing integer: " + e.getMessage());
}
}
writeToFile(filePath);
readFromFile(filePath);
}
}
Que 48: Write a program to show reading and writing with random access file.At the same time
append some text to a file.
Code:
import java.io.*;
// Close RandomAccessFile
randomAccessFile.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Close RandomAccessFile
randomAccessFile.close(); } catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
// Close FileWriter
fileWriter.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Que 49: Write an applet program to print Hello.
Code:
import java.applet.Applet; import
java.awt.*;
Hello
// Initialization method
public void init() {
// Get the value of the "message" parameter
message = getParameter("message");
Output:
/**
*
* @author DS
*/ import
java.applet.Applet; import
java.awt.*; import
java.awt.event.*;
// Display result
resultLabel.setText("Result: " + result);
}
}
Output:
Que 52: Write a program to draw various shapes (at least 5) using methods of
graphics class.
Code:
import java.applet.Applet; import
java.awt.*;
// Initialization method
public void init() {
setBackground(Color.white);
}
// Draw an oval
g.setColor(Color.red);
g.fillOval(200, 50, 100, 50);
// Draw a line
g.setColor(Color.green);
g.drawLine(50, 150, 150, 150);
// Draw an arc
g.setColor(Color.magenta);
g.fillArc(200, 200, 100, 100, 90, 180);
}
}
Output:
Que 53: Write an applet program to draw bar charts.
Turnover (Rs.
Crores) 110 150 135 200 210 185
Code:
import java.applet.Applet; import
java.awt.*;
// Initialization method
public void init() {
setBackground(Color.white);
}
// Draw x-axis
g.drawLine(startX, height - 50, startX + chartWidth, height - 50);
// Draw y-axis
g.drawLine(startX, height - 50, startX, 50);
Output:
Que54: Write an applet program to insert image, audio and video
data.
Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * and open the template in the
editor.
*/
package applet.programs;
/**
*
* @author DS
*/ import
java.applet.*; import
java.awt.*; import
java.net.*;
// Load image
try {
URL imageURL = new URL(getDocumentBase(), "../images/image.jpg");
image = getImage(imageURL); mediaTracker.addImage(image, 0); }
catch (MalformedURLException e) { e.printStackTrace();
}
// Load audio
try {
URL audioURL = new URL(getDocumentBase(), "../sound/audio.wav");
audioClip = getAudioClip(audioURL); mediaTracker.addImage(image,
1); } catch (MalformedURLException e) { e.printStackTrace();
}
}
// Play audio if
(mediaTracker.checkID(1)) {
audioClip.play();
}
}
}
MyThread(String name) {
threadName = name;
}
Que57: Write a program to create server application that uses the Socket class
to listen for clients on a port number specified by a command-line argument:
Code: import java.io.*; import java.net.*;
while (true) {
// Wait for a client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket);
// Create a LinkedList
LinkedList<String> linkedList = new LinkedList<>();
System.out.println("\nModified LinkedList:");
for (String gameConsole : linkedList) {
System.out.println(gameConsole);
}
}
}
Output:
Que 59: Write a program to show how Vector class can be used.
Code:
import java.util.Vector;
Output: