You are on page 1of 51

Que 31. Assume that the bank maintains two kinds of account.

One called Saving Account


and the other is Current Account. The saving account provides compound interest and
withdrawal facility but no cheque book facility. The current account provides cheque book
facility and withdrawal facility but no interest. Current account holders should also maintains
a minimum balance and if the balance falls below this level, a service charge is imposed.
Create a class Account that stores customer name, account number, and the type of
account. From this derive the class curr_acct and sav_acct to make them more specific to
their requirement. Include the necessary methods in order to achieve the following task. •
Accept deposit from customer and update the balance.
• Display the balance.
• Permit withdrawal and compute the balance.
• Check for minimum balance, impose penalty if necessary and update the
balance. Display all the desired information.

Code:
import java.util.Scanner;

class Account
{
private String customerName;
private int accountNumber;
protected double balance;
protected String accountType;

public Account(String customerName, int accountNumber, double balance, String


accountType) {
this.customerName = customerName;
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposit of $" + amount + " successful.");
}

public void displayBalance() {


System.out.println("Account Balance: $" + balance);
}

public void withdraw(double amount) {


if (balance >= amount) { balance -=
amount;
System.out.println("Withdrawal of
$" + amount + " successful.");
} else {
System.out.println("Insufficient balance.");
}
}

public void checkMinimumBalance(double minimumBalance, double penalty)


{ if (balance < minimumBalance) { balance -= penalty;
System.out.println("Minimum balance penalty charged. Remaining balance: $" +
balance);
}
}
}

class SavingsAccount extends Account {


private double interestRate;

public SavingsAccount(String customerName, int accountNumber, double balance, double


interestRate) {
super(customerName, accountNumber, balance, "Savings");
this.interestRate = interestRate;
}
public void calculateInterest() {
balance += (balance * interestRate / 100);
System.out.println("Compound interest calculated. Updated balance: $" + balance);
}
}

class CurrentAccount extends Account {


public double minimumBalance;
public double penalty;

public CurrentAccount(String customerName, int accountNumber, double balance, double


minimumBalance, double penalty) {
super(customerName, accountNumber, balance, "Current");
this.minimumBalance = minimumBalance;
this.penalty = penalty;
}

@Override
public void checkMinimumBalance(double minimumBalance, double penalty) {
if (balance < minimumBalance) { balance -= penalty;
System.out.println("Minimum balance penalty charged. Remaining balance: $" +
balance);
}
}
}
public class Lab_31 {
public static void main(String[] args) {

System.out.println("Name : Harsh Kumar Nebhwani");


System.out.println("Reg. No. : 23FS20MCA00107");
Scanner scanner = new Scanner(System.in);

SavingsAccount savingsAccount = new SavingsAccount("John", 123456, 5000, 5);

CurrentAccount currentAccount = new CurrentAccount("Alice", 987654, 3000, 2000,


50);

savingsAccount.deposit(2000);

currentAccount.withdraw(1000);

currentAccount.checkMinimumBalance(currentAccount.minimumBalance,
currentAccount.penalty);

System.out.println("\nSavings Account:");
savingsAccount.displayBalance();

System.out.println("\nCurrent Account:"); currentAccount.displayBalance();

scanner.close();
}
}

Output:

Que 32. Write a program to show the use of super.


Code:
class Parent {
int parentData;

public Parent(int parentData)


{ this.parentData = parentData;
System.out.println("Parent class constructor called.");
}

public void displayParentData() {


System.out.println("Parent Data: " + parentData);
}
}

class Child extends Parent {


int childData;

public Child(int parentData, int childData) { super(parentData);


this.childData = childData;
System.out.println("Child class constructor called.");
}
public void displayChildData() {
System.out.println("Child Data: " + childData);
}

@Override
public void displayParentData() { super.displayParentData();
Calling parent class method using super
System.out.println("Overridden method in Child class.");
}
}

public class LAB_32 { public static


void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107");
Child childObj = new Child(10, 20);

childObj.displayParentData();
childObj.displayChildData();
}
}
Output:

Que 33. Assume that the publishing company markets print books and digital
books. Create a class named Publication with data members named title, price
and authors name. from Publication class derive two classes named Books and
Ebooks. The Book class adds a page count data member named pcount while
Ebook adds data member playing time name ptime. Each of the classes must
have member functions getdata() to read class specific data from keyboard and
displaydata() to output the class specific data to the computer screen. Write a
Program to test these classes.

Code:
import java.util.Scanner;

class Publication {
String title;
double price;
String authorName;

public void getData() {


Scanner scanner = new Scanner(System.in);
System.out.println("Enter publication title: "); title
= scanner.nextLine();
System.out.println("Enter publication price: "); price
= scanner.nextDouble(); scanner.nextLine();
System.out.println("Enter author's name: ");
authorName = scanner.nextLine();
}
public void displayData() {
System.out.println("Title: " + title);
System.out.println("Price: $" + price);
System.out.println("Author's Name: " + authorName);
}
}

class Book extends Publication {


int pageCount;

@Override
public void getData() {
super.getData();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter page count: "); pageCount
= scanner.nextInt();
}

@Override
public void displayData()
{ super.displayData();
System.out.println("Page Count: " + pageCount);
}
}

class Ebook extends Publication {


int playingTime;

@Override
public void getData() {
super.getData();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter playing time (in minutes): ");
playingTime = scanner.nextInt();
}

@Override
public void displayData()
{ super.displayData();
System.out.println("Playing Time: " + playingTime + " minutes");
}
}

public class LAB_33 {


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

System.out.println("Enter details for a book:");


Book book = new Book();
book.getData();
System.out.println("\nBook details:");
book.displayData();
System.out.println("\nEnter details for an ebook:");
Ebook ebook = new Ebook();
ebook.getData();
System.out.println("\nEbook details:");
ebook.displayData(); scanner.close();
}

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;

double area();
double perimeter();
}
class Circle implements Shape {
private double radius;

public Circle(double
radius) {
this.radius = radius;
}
public double area() { return PI * radius * radius;
}
public double perimeter() {
return 2 * PI * radius;
}
}

class Rectangle implements Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public double area() {


return length * width;
}

public double perimeter() {


return 2 * (length + width);
}
}

class Square implements Shape {


private double side;

public Square(double side) {


this.side = side;
}
public double area() {
return side * side;
}
public double perimeter() { return 4 * side;
}
}

public class LAB_34 {


public static void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107");

Circle circle = new Circle(5);


Rectangle rectangle = new Rectangle(4, 6);
Square square = new Square(3);

System.out.println("Circle:");
System.out.println("Area: " + circle.area());
System.out.println("Perimeter: " + circle.perimeter());

System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.area());
System.out.println("Perimeter: " + rectangle.perimeter());

System.out.println("\nSquare:");
System.out.println("Area: " + square.area());
System.out.println("Perimeter: " + square.perimeter());
}
}
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 {

int binaryToDecimal(String binary);

String decimalToBinary(int decimal);

String twosComplement(String binary);

String binaryAddition(String binary1, String binary2);


}

public class LAB_35 implements Binary {

public int binaryToDecimal(String binary) {


return Integer.parseInt(binary, 2);
}

public String decimalToBinary(int decimal) {


return Integer.toBinaryString(decimal);
}

public
String twosComplement(String binary)
{ StringBuilder complement = new StringBuilder();
for (char bit : binary.toCharArray()) {
complement.append((bit == '0') ? '1' : '0');
}
return complement.toString();
}

public String binaryAddition(String binary1, String


binary2) {
int carry = 0;
StringBuilder sum = new StringBuilder();
int i = binary1.length() - 1;
int j = binary2.length() - 1;

while (i >= 0 || j >= 0 || carry > 0) {


int bit1 = (i >= 0) ? binary1.charAt(i--) - '0' : 0;
int bit2 = (j >= 0) ? binary2.charAt(j--) - '0' : 0; int
currentSum = bit1 + bit2 + carry; sum.insert(0,
currentSum % 2); carry =
currentSum / 2;
}

return sum.toString();
}

public static void main(String[] args) {


LAB_35 obj = new LAB_35();

String binary = "1010";


int decimal = obj.binaryToDecimal(binary);
System.out.println("Binary: " + binary + " Decimal: " + decimal);

int number = 10;


String binaryString = obj.decimalToBinary(number);
System.out.println("Decimal: " + number + " Binary: " + binaryString);

String originalBinary = "1010";


String complement = obj.twosComplement(originalBinary);
System.out.println("Original Binary: " + originalBinary + " Two's Complement: " +
complement);
String binary1 = "101";
String binary2 = "110";
String sum = obj.binaryAddition(binary1, binary2);
System.out.println("Binary Addition: " + binary1 + " + " + binary2 + " = " + sum);
}
}

Que 36: Write a program to display the use of all access modifiers with the
help of two packages.
Code:
package package_1;

public class PublicClass {


public void publicMethod() {
System.out.println("This is a public method in Package 1");
}

protected void protectedMethod() {


System.out.println("This is a protected method in Package 1");
}

void defaultMethod() {
System.out.println("This is a default method in Package 1");
}

private void privateMethod() {


System.out.println("This is a private method in Package 1");
}
}

package package2;

import package_1.PublicClass;

public class LAB_36 { public static


void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107");
PublicClass obj = new PublicClass(); obj.publicMethod();

}
}
Out

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 studentPackage;

public class Student


{ private int rollNo;
private int paper1; private
int paper2;

public Student(int rollNo, int paper1, int paper2)


{ this.rollNo = rollNo; this.paper1 = paper1;
this.paper2 = paper2;
}

public int calculateTotalScore()


{ return paper1 + paper2; \
}

public void displayDetails() {


System.out.println("Roll No: " + rollNo);
System.out.println("Paper 1 Score: " + paper1);
System.out.println("Paper 2 Score: " + paper2);
System.out.println("Total Score: " + calculateTotalScore());
}
}

sportsPackage;

public interface Sports {


int getSportsScore();
}

import studentPackage.Student; import


sportsPackage.Sports;

public class LAB_37 implements Sports


{ public int getSportsScore() {
return 80;
}

public static void main(String[] args) { System.out.println("Name : HARSH KUMAR


NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

Student student = new Student(101, 75, 85);


LAB_37 obj = new LAB_37();

student.displayDetails();

System.out.println("Sports Score: " + obj.getSportsScore());


}
}

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 : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107"); try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e.getMessage());


}

System.out.println("Program completed.");
}

public static int divide(int dividend, int divisor) {


return dividend / divisor;
}
}

Output:
Que 39: Write a program to show the use of nested try/catch statements.
Code:
public class LAB_39 { public static void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107"); try {

System.out.println("Outer try block starts");


try
{

System.out.println("Inner try block starts");

int result = divide(10, 0);

System.out.println("Result: " + result); // This line won't be executed if an


exception occurs

System.out.println("Inner try block ends");


} catch (ArithmeticException e) {

System.out.println("Inner catch block: " + e.getMessage());


}
System.out.println("Outer try block ends");
} catch (Exception e) {

System.out.println("Outer catch block: " + e.getMessage());


}

System.out.println("Program completed.");
}

public static int divide(int dividend, int divisor)


{ return dividend / divisor;
}
}

Output:

Q40.Write a program to show the use of “throw”, “throws” and “finally”


keyword.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LAB_40 { public static
void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107"); try
{
readFromFile("nonexistentfile.txt");
} catch (IOException e) {

System.out.println("Exception caught: " + e.getMessage());


} finally {

System.out.println("Finally block executed");


}
}

public static void readFromFile(String fileName) throws IOException {


BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw e; } finally {
if (reader != null) { try {
reader.close();
} catch (IOException e) {

}
Que41: Write a program to create a custom exception. Show its use with the
help o java program. Code:
class CustomException extends Exception {

CustomException(String message) { super(message);


}
}

public class LAB_41 {


public static void checkNumber(int number) throws CustomException { if
(number <
0) { throw new CustomException("Number cannot be negative");
} else {
System.out.println("Number is valid: " + number);
}
}

public static void main(String[] args) {

System.out.println("Name : HARSH KUMAR NEBHWANI");


System.out.println("Reg. No. : 23FS20MCA00107"); try
{
checkNumber(-5);
} catch (CustomException e) {

System.out.println("Custom Exception caught: " + e.getMessage());


}
}
}
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;
class InvalidInputException extends Exception { public
InvalidInputException(String message) { super(message);
}
}

public class LAB_42 { public static


void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");
Scanner scanner = new Scanner(System.in); try
{

System.out.print("Enter first number: "); int


num1 = readInteger(scanner);
System.out.print("Enter second number: "); int
num2 = readInteger(scanner);

int result = divide(num1, num2);


System.out.println("Result of division: " + result);

} catch (InvalidInputException e) {

System.out.println("Invalid input: " + e.getMessage());


} catch (ArithmeticException e) {

System.out.println("Division by zero: " + e.getMessage());


} finally {
scanner.close();
}
}

public static int readInteger(Scanner scanner) throws InvalidInputException


{ if
(scanner.hasNextInt()) { return scanner.nextInt();
} else { throw new InvalidInputException("Input is not an
integer");
}
}

public static int divide(int num1, int num2) { if (num2 == 0) {


throw new
ArithmeticException("Cannot divide by zero");
}
return num1 / num2;
}
}
Que43: Define an exception called “NoMatchException” that is thrown when a
string is not equal to “India”. Write a program that uses this exception.
Code:
class NoMatchException class
NoMatchException extends Exception { public
NoMatchException(String message) {
super(message);
}
}

public class LAB_43 {


public static void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107"); try
{
String country = "USA";

if (!country.equals("India")) {
throw NoMatchException
throw new NoMatchException("String does not match 'India'");
} else {

System.out.println("String matches 'India'");


}
} catch (NoMatchException e) {

System.out.println("NoMatchException caught: " + e.getMessage());


}
}
}

Que44: Write a program to copy characters from one file into another using
character streams.
Code:
import java.io.*;

public class LAB_44 { public static


void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

String inputFile = "src/input.txt";


String outputFile = "output.txt";
try
{

FileReader fileReader = new FileReader(inputFile);


FileWriter fileWriter = new FileWriter(outputFile);

BufferedReader and BufferedWriter objects


BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String line; while ((line = bufferedReader.readLine())


!= null) { bufferedWriter.write(line); bufferedWriter.newLine();
}

bufferedReader.close();
bufferedWriter.close();

System.out.println("File copied successfully.");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

Que45: Write a program to write bytes to a file.


Code:
import java.io.*;
public class LAB_45 {
public static void main(String[] args) {

String filePath = "output.txt";


byte[] bytesToWrite = {65, 66, 67, 68, 69};
try
{

FileOutputStream outputStream = new FileOutputStream(filePath);

outputStream.write(bytesToWrite);

outputStream.close();
System.out.println("Bytes written to the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Outp

Que46: Write a program to read bytes from file by using program


no47.
Code:
import java.io.*;

public class LAB_46 {


public static void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

String filePath = "output.txt";


try
{

FileInputStream inputStream = new FileInputStream(filePath);

int byteRead;
while ((byteRead = inputStream.read()) != -1) {
System.out.print((char) byteRead);
}

inputStream.close();

} 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.*;

public class LAB_47 {


public static void writeToFile(String filePath)
{
try {

FileWriter fileWriter = new FileWriter(filePath);

String[] students = {
"101,John,10,A,80,75,85",
"102,Alice,10,B,70,65,80",
"103,Smith,11,A,85,80,90",
"104,Emily,11,B,75,70,80",
"105,David,12,A,90,85,95"
};

for (String student : students) {


fileWriter.write(student + "\n");
}

fileWriter.close();

System.out.println("Student details written to file successfully.");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}

public static void readFromFile(String filePath) { try {

FileReader fileReader = new FileReader(filePath);


BufferedReader bufferedReader = new BufferedReader(fileReader);

String line; while ((line =


bufferedReader.readLine()) != null) {
String[] details = line.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]);

int totalMarks = marks1 + marks2 + marks3;

System.out.println("Student ID: " + id);


System.out.println("Name: " + name);
System.out.println("Class: " + classNo);
System.out.println("Semester: " + semester);
System.out.println("Subject 1 Marks: " + marks1);
System.out.println("Subject 2 Marks: " + marks2);
System.out.println("Subject 3 Marks: " + marks3);
System.out.println("Total Marks: " + totalMarks);
System.out.println();
}

bufferedReader.close();

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}

public static void main(String[] args) {


System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");
String filePath = "students.txt";

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.*;

public class LAB_48 { public static


void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

String filePath = "random_access.txt";

writeToFile(filePath);

readFromFile(filePath);

appendToFile(filePath, "This text is appended to the file.");

readFromFile(filePath);
}

public static void writeToFile(String filePath) {


try {

RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");

randomAccessFile.writeUTF("John");
randomAccessFile.writeInt(25); randomAccessFile.writeDouble(85.5);

randomAccessFile.close();

System.out.println("Data written to random access file successfully.");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}

public static void readFromFile(String filePath) {


try {

RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");

randomAccessFile.seek(0);

String name = randomAccessFile.readUTF();


int age = randomAccessFile.readInt(); double
marks = randomAccessFile.readDouble();

System.out.println("Name: " + name);


System.out.println("Age: " + age);
System.out.println("Marks: " + marks);

randomAccessFile.close(); } catch (IOException e) {


System.out.println("An error occurred: " + e.getMessage());

}
}

public static void appendToFile(String filePath, String text) { try {

FileWriter fileWriter = new FileWriter(filePath, true);

fileWriter.write("\n" + text);

fileWriter.close();

System.out.println("Text appended to file successfully.");

} 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.*;

public class LAB_49 extends Applet {


public void paint(Graphics g) {
g.drawString("Hello", 50, 50);
}
}
Output:

Que 50: Write an applet program to print Hello by passing parameter. Code:
import java.applet.Applet;
import java.awt.*;

public class LAB_50 extends Applet {

String message;

public void init() {


message = getParameter("message");

if (message == null) { message = "Hello";


}
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}
}

Output:

Que 51: Write a program to perform the arithmetic operations by using


interactive inputs to an applet.
package applet.programs;
import java.applet.Applet; import java.awt.*;
import java.awt.event.*;

public class LAB_51 extends Applet implements ActionListener {

TextField num1Field, num2Field;

Label num1Label, num2Label, resultLabel;


Button addButton, subtractButton, multiplyButton, divideButton;

public void init() {


TextFields num1Field = new
TextField(10); num2Field = new
TextField(10);
Labels num1Label = new
Label("Enter first number:");
num2Label = new Label("Enter
second number:"); resultLabel =
new Label("");

addButton = new
Button("Add"); subtractButton = new
Button("Subtract"); multiplyButton = new
Button("Multiply"); divideButton = new
Button("Divide");

addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);

add(num1Label);
add(num1Field); add(num2Label);
add(num2Field); add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
add(resultLabel);
}

public void actionPerformed(ActionEvent e) {


TextFields double num1 =
Double.parseDouble(num1Field.getText()); double num2 =
Double.parseDouble(num2Field.getText()); double result = 0;

if (e.getSource() == addButton) { result = num1 +


num2;
} else if (e.getSource() == subtractButton)
{ result = num1 - num2;

} else if (e.getSource() == multiplyButton)


{ result = num1 * num2;
} else if (e.getSource() == divideButton) {
if (num2 != 0) {
result = num1 / num2;
} else { resultLabel.setText("Cannot divide
by zero"); return;
}
}

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.*;

public class LAB_52 extends Applet {


public void init()
{ setBackground(Color.white
);
}

public void paint(Graphics g)


{
g.setColor(Color.blue);
g.fillRect(50, 50, 100, 50);

g.setColor(Color.red);
g.fillOval(200, 50, 100, 50);

g.setColor(Color.green);
g.drawLine(50, 150, 150, 150);

int[] xPoints = {250, 300, 350};


int[] yPoints = {200, 150, 200}; int
nPoints = 3;
g.setColor(Color.orange);
g.fillPolygon(xPoints, yPoints, nPoints);

g.setColor(Color.magenta);
g.fillArc(200, 200, 100, 100, 90, 180);
}
}
Output:
Que 53: Write an applet program to draw bar charts.

Year 2009 2010 2011 2012 2013 2014

Turnover (Rs.
Crores) 110 150 135 200 210 185

Code:
import java.applet.Applet;
import java.awt.*;

public class LAB_53 extends Applet {

String[] years = {"2009", "2010", "2011", "2012", "2013", "2014"}; int[]


turnover = {110, 150, 135, 200, 210, 185};

public void init()


{ setBackground(Color.white
);
}
public void paint(Graphics g) {
int width = getWidth(); int
height = getHeight();
int barWidth = 50; int gap = 20; int startX = 50; int startY = 50; int
chartWidth = (barWidth + gap) * years.length; int maxTurnover =
getMax(turnover); int scale = (height - 100) / maxTurnover;

g.drawLine(startX, height - 50, startX + chartWidth, height - 50);

g.drawLine(startX, height - 50, startX, 50);

for (int i = 0; i < years.length; i++) {


int barHeight = turnover[i] * scale;
g.setColor(Color.blue);
g.fillRect(startX + (barWidth + gap) * i, height - 50 - barHeight, barWidth, barHeight);

g.setColor(Color.black);
g.drawString(years[i], startX + (barWidth + gap) * i + 10, height - 30);

g.drawString(Integer.toString(turnover[i]), startX + (barWidth + gap) * i + 10, height -


50 - barHeight - 5);
}
}
public int getMax(int[] array) { int max =
array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) { max = array[i];
}
}
return max;
}
}

Output:
Que54: Write an applet program to insert image, audio and video
data.
Code:

package applet.programs;

import java.applet.*;
import java.awt.*;
import java.net.*;

public class LAB_54 extends Applet {


private Image image; private
AudioClip audioClip; private
MediaTracker mediaTracker;

public void init() {


MediaTracker mediaTracker = new
MediaTracker(this);

try {
URL imageURL = new URL(getDocumentBase(), "../images/image.jpg");
image = getImage(imageURL); mediaTracker.addImage(image, 0); }
catch (MalformedURLException e) { e.printStackTrace();
}
try {
URL audioURL = new URL(getDocumentBase(), "../sound/audio.wav");
audioClip = getAudioClip(audioURL); mediaTracker.addImage(image, 1);
} catch (MalformedURLException e) { e.printStackTrace();
}
}

public void paint(Graphics g) {


if
(mediaTracker.checkID(0)) {
g.drawImage(image, 0, 0, this);
}

if
(mediaTracker.checkID(1)) { audioClip.play();
}
}
}
Que55: Write a program to illustrate the use of multithreading. Also set
priorities for threads.
Code: class MyThread extends Thread { private String threadName;

MyThread(String name)
{ threadName = name;
}

public void run() { for


(int i = 1; i <= 5; i++) {
System.out.println(threadName + ": " + i);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}
}

public class LAB_55 { public static


void main(String args[]) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");

hread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}
}

Que56: Write a program that connects to a server by using a socket and sends
a greeting, and then waits for a response.
Code:
import java.io.*;
import java.net.*;

public class LAB_56 { public static


void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");
String serverAddress = "localhost";
int port = 12345;
try
{

Socket socket = new Socket(serverAddress, port);

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

System.out.println("Hello from client!");


String response = in.readLine();
System.out.println("Server response: " + response);
socket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

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.*;

public class LAB_57 { public static


void main(String[] args) { if
(args.length != 1) {
System.err.println("Usage: java LAB_57 <port>");
return;
}

int port = Integer.parseInt(args[0]);

try (ServerSocket serverSocket = new ServerSocket(port))


{ System.out.println("Server started. Listening on port " + port);

while (true) {

Socket clientSocket = serverSocket.accept();


System.out.println("Client connected: " + clientSocket);

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream())); PrintWriter
out = new PrintWriter(clientSocket.getOutputStream(), true);

String message = in.readLine();


System.out.println("Message from client: " + message);

System.out.println("Hello from server!");


clientSocket.close();
System.out.println("Client disconnected.");
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}}
Out

Que58: Write a program to show the use of methods of the ArrayList and
LinkedList classes.
Code:
import java.util.ArrayList;
import java.util.LinkedList;

public class LAB_58 { public static


void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");
ArrayList<String> arrayList = new ArrayList<>();

arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");

System.out.println("ArrayList:");
for (String fruit : arrayList) {
System.out.println(fruit);
}
LinkedList<String> linkedList = new LinkedList<>();

linkedList.add("Xbox");
linkedList.add("PlayStation");
linkedList.add("Nintendo");
System.out.println("\nLinkedList:"); for
(String gameConsole : linkedList) {
System.out.println(gameConsole);
}

arrayList.add(1, "Orange");

linkedList.removeLast();

ArrayList and LinkedList


System.out.println("\nModified ArrayList:"); for
(String fruit : arrayList) {
System.out.println(fruit);
}

System.out.println("\nModified LinkedList:"); for


(String gameConsole : linkedList) {
System.out.println(gameConsole);
}
}
}
Que 59: Write a program to show how Vector class can be used.
Code:
import java.util.Vector;

public class VectorExample { public


static void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

Vector<String> vector = new Vector<>();

vector.add("Apple"); vector.add("Banana");
vector.add("Orange");

System.out.println("Elements in the Vector:");


for (String fruit : vector)
{ System.out.println(fruit);
}

System.out.println("Size of the Vector: " + vector.size());

vector.remove("Banana");

if (vector.contains("Banana")) {
System.out.println("Vector contains Banana");
} else {
System.out.println("Vector does not contain Banana");
}

vector.clear();

if (vector.isEmpty()) {
System.out.println("Vector is empty");
} else {
System.out.println("Vector is not empty");
}
}

Que 60: Write a program to search an element in a collection using


binarySearch method.

Code:
import java.util.ArrayList;
import java.util.Collections;

public class BinarySearchExample {


public static void main(String[] args) {
System.out.println("Name : HARSH KUMAR NEBHWANI");
System.out.println("Reg. No. : 23FS20MCA00107");

ArrayList<Integer> numbers = new ArrayList<>();


numbers.add(10); numbers.add(20); numbers.add(30);
numbers.add(40);
numbers.add(50);

(binarySearch requires a sorted collection) Collections.sort(numbers);

int target = 30;

int index = Collections.binarySearch(numbers, target);

if (index >= 0) {
System.out.println("Element " + target + " found at index " + index);
} else {
System.out.println("Element " + target + " not found");
}
}
}

You might also like