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

java

Uploaded by

fogok93828
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java

Uploaded by

fogok93828
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Write a ‘java’ program to display characters from ‘A’ to ‘Z’.

import java.io.*;

class Main {

public static void main(String[] args) {

char c;

for(c = 'A'; c <= 'Z'; ++c)

System.out.print(c + " ");

Write a ‘java’ program to copy only non-numeric data from one file to another file.

import java.io.*;

import java.util.*;

class Copyfile {

public static void main(String arg[]) throws Exception {

Scanner sc = new Scanner(System.in);

System.out.print("source file name :");

String sfile = sc.next();

System.out.print("destination file name :");

String dfile = sc.next();

FileReader fin = new FileReader(sfile);

FileWriter fout = new FileWriter(dfile, true);

int c;

while ((c = fin.read()) != -1) {

fout.write(c);

System.out.println("Copy finish...");

fin.close();

fout.close();

}
Write a ‘java’ program to display characters from ‘A’ to ‘Z’.

import java.io.*;

class Main {

public static void main(String[] args) {

char c;

for(c = 'A'; c <= 'Z'; ++c)

System.out.print(c + " ");

Write a ‘java’ program to copy only non-numeric data from one file to another file.

import java.io.*;

import java.util.*;

class Copyfile {

public static void main(String arg[]) throws Exception {

Scanner sc = new Scanner(System.in);

System.out.print("source file name :");

String sfile = sc.next();

System.out.print("destination file name :");

String dfile = sc.next();

FileReader fin = new FileReader(sfile);

FileWriter fout = new FileWriter(dfile, true);

int c;

while ((c = fin.read()) != -1) {


fout.write(c);

System.out.println("Copy finish...");

fin.close();

fout.close();

Write a java program to display all the vowels from a given string.

import java.io.*;

class Vowel {

public static void main(String args[]) {

String str = new String("HI WElcome!");

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

if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'||

str.charAt(i) == 'i' || str.charAt(i) == 'o' ||

str.charAt(i) == 'u'||str.charAt(i) == 'A'|| str.charAt(i) == 'E'||

str.charAt(i) == 'I' || str.charAt(i) == 'O' ||

str.charAt(i) == 'U')

System.out.println("Given string contains " +

str.charAt(i)+" at the index " + i);

Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the
position of the Mouse_Click in a TextField.

import java.awt.*;
import java.awt.event.*;

class Slip4 extends Frame

TextField statusBar;

Slip4()

addMouseListener(new MouseAdapter()

public void mouseClicked(MouseEvent e)

statusBar.setText("Clicked at (" +e.getX() + "," + e.getY() + ")");

repaint();

public void mouseEntered(MouseEvent e)

statusBar.setText("Entered at (" + e.getX() + "," +e.getY() + ")");

repaint();

});

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent e)

System.exit(0);

});

setLayout(new FlowLayout());

setSize(275,300);

setTitle("Mouse Click Position");

statusBar = new TextField(20);


add(statusBar);

setVisible(true);

public static void main(String []args)

new Slip4();

Write a java program to display all the vowels from a given string.

import java.io.*;

class Vowel {

public static void main(String args[]) {

String str = new String("HI WElcome!");

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

if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'||

str.charAt(i) == 'i' || str.charAt(i) == 'o' ||

str.charAt(i) == 'u'||str.charAt(i) == 'A'|| str.charAt(i) == 'E'||

str.charAt(i) == 'I' || str.charAt(i) == 'O' ||

str.charAt(i) == 'U')

System.out.println("Given string contains " +

str.charAt(i)+" at the index " + i);

Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the
position of the Mouse_Click in a TextField.

import java.awt.*;
import java.awt.event.*;

class Slip4 extends Frame

TextField statusBar;

Slip4()

addMouseListener(new MouseAdapter()

public void mouseClicked(MouseEvent e)

statusBar.setText("Clicked at (" +e.getX() + "," + e.getY() + ")");

repaint();

public void mouseEntered(MouseEvent e)

statusBar.setText("Entered at (" + e.getX() + "," +e.getY() + ")");

repaint();

});

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent e)

System.exit(0);

});

setLayout(new FlowLayout());

setSize(275,300);

setTitle("Mouse Click Position");

statusBar = new TextField(20);


add(statusBar);

setVisible(true);

public static void main(String []args)

new Slip4();

Write a ‘java’ program to check whether given number is Armstrong or not.(Use static keyword)

import java.util.Scanner;

public class ArmstsrongNumber

static int num, temp, res=0, rem;

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

System.out.print("Enter the Number: ");

num = scan.nextInt();

temp = num;

while(temp!=0)

rem = temp%10;

res = res + (rem*rem*rem);

temp = temp/10;

if(num==res)
System.out.println("\nArmstrong Number.");

else

System.out.println("\nNot an Armstrong Number.");

Define an abstract class Shape with abstract methods area () and volume (). Derive abstract class Shape into two
classes Cone and Cylinder. Write a java Program to calculate area and volume of Cone and Cylinder.(Use Super
Keyword.)

import java.util.*;

abstract class Shape

abstract public void area();

abstract public void vol();

class Cone extends Shape

int r,s,h;

Cone(int r,int s,int h)

super();

this.r=r;

this.s=s;

this.h=h;

public void area()

System.out.println("Area of Cone = "+(3.14*r*s));

public void vol()

System.out.println("volume of Cone = "+(3.14*r*r*h)/3);


}

class Cylinder extends Shape

int r,h;

Cylinder(int r,int h)

this.r=r;

this.h=h;

public void area()

{ System.out.println("Area of Cylinder = "+(2*3.14*r*h));

public void vol()

System.out.println("volume of Cylinder = "+(3.14*r*r*h));

class Slip15

public static void main(String a[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter radius, side and height for cone");

int r =sc.nextInt();

int s1 =sc.nextInt();

int h =sc.nextInt();

Shape s;

s=new Cone(r,s1,h);

s.area();
s.vol();

System.out.println("Enter radius, height for cylinder");

r =sc.nextInt();

h =sc.nextInt();

s=new Cylinder(r,h);

s.area();

s.vol();

Write a ‘java’ program to check whether given number is Armstrong or not.(Use static keyword)

import java.util.Scanner;

public class ArmstsrongNumber

static int num, temp, res=0, rem;

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

System.out.print("Enter the Number: ");

num = scan.nextInt();

temp = num;

while(temp!=0)

rem = temp%10;

res = res + (rem*rem*rem);


temp = temp/10;

if(num==res)

System.out.println("\nArmstrong Number.");

else

System.out.println("\nNot an Armstrong Number.");

Define an abstract class Shape with abstract methods area () and volume (). Derive abstract class Shape into two
classes Cone and Cylinder. Write a java Program to calculate area and volume of Cone and Cylinder.(Use Super
Keyword.)

import java.util.*;

abstract class Shape

abstract public void area();

abstract public void vol();

class Cone extends Shape

int r,s,h;

Cone(int r,int s,int h)

super();

this.r=r;

this.s=s;

this.h=h;

public void area()

System.out.println("Area of Cone = "+(3.14*r*s));

}
public void vol()

System.out.println("volume of Cone = "+(3.14*r*r*h)/3);

class Cylinder extends Shape

int r,h;

Cylinder(int r,int h)

this.r=r;

this.h=h;

public void area()

{ System.out.println("Area of Cylinder = "+(2*3.14*r*h));

public void vol()

System.out.println("volume of Cylinder = "+(3.14*r*r*h));

class Slip15

public static void main(String a[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter radius, side and height for cone");

int r =sc.nextInt();

int s1 =sc.nextInt();

int h =sc.nextInt();
Shape s;

s=new Cone(r,s1,h);

s.area();

s.vol();

System.out.println("Enter radius, height for cylinder");

r =sc.nextInt();

h =sc.nextInt();

s=new Cylinder(r,h);

s.area();

s.vol();

Slip4

Write a java program to display alternate character from a given string.

import java.util.Scanner;

public class Main

public static void main(String str[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter an string");

String str1 = sc.nextLine();

try{

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

System.out.println(str1.charAt(i));

} catch(StringIndexOutOfBoundsException e) {
System.out.println("String index out of bounds. String length: " + str1.length());

Write a java program using Applet to implement a simple arithmetic calculator.

Calculator.java

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class Calculator extends Applet implements ActionListener

String str = " ";

int v1, v2, result;

TextField t1;

Button b[] = new Button[10];

Button add, sub, mul, div, clear, mod, equals;

char choice;

public void init()

Color k = new Color(120, 89, 90);

setBackground(k);

t1 = new TextField(10);

GridLayout g1 = new GridLayout(4, 5);

setLayout(g1);

for (int i = 0; i < 10; i++)

b[i] = new Button("" + i);

add = new Button("add");


sub = new Button("sub");

mul = new Button("mul");

div = new Button("div");

mod = new Button("mod");

clear = new Button("clear");

equals = new Button("equals");

t1.addActionListener(this);

add(t1);

for (int i = 0; i < 10; i++)

add(b[i]);

add(add);

add(sub);

add(mul);

add(div);

add(mod);

add(clear);

add(equals);

for (int i = 0; i < 10; i++)

b[i].addActionListener(this);

add.addActionListener(this);

sub.addActionListener(this);

mul.addActionListener(this);

div.addActionListener(this);

mod.addActionListener(this);

clear.addActionListener(this);

equals.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)

String str = ae.getActionCommand();

char ch = str.charAt(0);

if (Character.isDigit(ch))

t1.setText(t1.getText() + str);

else

if (str.equals("add"))

v1 = Integer.parseInt(t1.getText());

choice = '+';

t1.setText("");

else if (str.equals("sub"))

v1 = Integer.parseInt(t1.getText());

choice = '-';

t1.setText("");

if (str.equals("mul"))

v1 = Integer.parseInt(t1.getText());

choice = '*';

t1.setText("");

if (str.equals("div"))

v1 = Integer.parseInt(t1.getText());
choice = '/';

t1.setText("");

if (str.equals("mod"))

v1 = Integer.parseInt(t1.getText());

choice = '%';

t1.setText("");

if (str.equals("clear"))

t1.setText("");

if (str.equals("equals"))

v2 = Integer.parseInt(t1.getText());

switch (choice)

case '+': result = v1 + v2;

break;

case '-': result = v1 - v2;

break;

case '*': result = v1 * v2;

break;

case '/': result = v1 / v2;

break;

case '%': result = v1 % v2;

break;

t1.setText("" + result);
}

Calculator.html

<applet code="Calculator.class" width=400 height=400></applet>

C:\Program Files\Java\jdk1.6.0\bin\Java Slips>javac Calculator.java

C:\Program Files\Java\jdk1.6.0\bin\Java Slips>appletviewer Calculator.html

Write a java program to display alternate character from a given string.

import java.util.Scanner;

public class Main

public static void main(String str[]) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter an string");

String str1 = sc.nextLine();

try{

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

System.out.println(str1.charAt(i));

} catch(StringIndexOutOfBoundsException e) {

System.out.println("String index out of bounds. String length: " + str1.length());

}
}

Write a java program using Applet to implement a simple arithmetic calculator.

Calculator.java

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class Calculator extends Applet implements ActionListener

String str = " ";

int v1, v2, result;

TextField t1;

Button b[] = new Button[10];

Button add, sub, mul, div, clear, mod, equals;

char choice;

public void init()

Color k = new Color(120, 89, 90);

setBackground(k);

t1 = new TextField(10);

GridLayout g1 = new GridLayout(4, 5);

setLayout(g1);

for (int i = 0; i < 10; i++)

b[i] = new Button("" + i);

add = new Button("add");

sub = new Button("sub");

mul = new Button("mul");


div = new Button("div");

mod = new Button("mod");

clear = new Button("clear");

equals = new Button("equals");

t1.addActionListener(this);

add(t1);

for (int i = 0; i < 10; i++)

add(b[i]);

add(add);

add(sub);

add(mul);

add(div);

add(mod);

add(clear);

add(equals);

for (int i = 0; i < 10; i++)

b[i].addActionListener(this);

add.addActionListener(this);

sub.addActionListener(this);

mul.addActionListener(this);

div.addActionListener(this);

mod.addActionListener(this);

clear.addActionListener(this);

equals.addActionListener(this);

public void actionPerformed(ActionEvent ae)


{

String str = ae.getActionCommand();

char ch = str.charAt(0);

if (Character.isDigit(ch))

t1.setText(t1.getText() + str);

else

if (str.equals("add"))

v1 = Integer.parseInt(t1.getText());

choice = '+';

t1.setText("");

else if (str.equals("sub"))

v1 = Integer.parseInt(t1.getText());

choice = '-';

t1.setText("");

if (str.equals("mul"))

v1 = Integer.parseInt(t1.getText());

choice = '*';

t1.setText("");

if (str.equals("div"))

v1 = Integer.parseInt(t1.getText());

choice = '/';

t1.setText("");
}

if (str.equals("mod"))

v1 = Integer.parseInt(t1.getText());

choice = '%';

t1.setText("");

if (str.equals("clear"))

t1.setText("");

if (str.equals("equals"))

v2 = Integer.parseInt(t1.getText());

switch (choice)

case '+': result = v1 + v2;

break;

case '-': result = v1 - v2;

break;

case '*': result = v1 * v2;

break;

case '/': result = v1 / v2;

break;

case '%': result = v1 % v2;

break;

t1.setText("" + result);

}
}

Calculator.html

<applet code="Calculator.class" width=400 height=400></applet>

C:\Program Files\Java\jdk1.6.0\bin\Java Slips>javac Calculator.java

C:\Program Files\Java\jdk1.6.0\bin\Java Slips>appletviewer Calculator.html

Write a java program to display following pattern:

45

345

2345

12345

import java.io.*;

public class Pattern

public static void main(String[] args){

for (int i = 1; i <= 5; i++) {

for (int j = 5; j >= i; j--)

{
System.out.print(j + " ");

System.out.println();

Slip12.Write a java program to accept list of file names through command line and delete the files having extension
“.txt”. Display the details of remaining files such as FileName and size.

import java.io.*;
class Slip12
{
public static void main(String args[]) throws Exception
{
for(int i=0;i<args.length;i++)
{
File file=new File(args[i]);
if(file.isFile())
{
String name = file.getName();
if(name.endsWith(".txt"))
{
file.delete();
System.out.println("file is deleted " + file);
}
else
{
System.out.println(name + " "+file.length()+" bytes");
}
}
else
{
System.out.println(args[i]+ "is not a file");
}
}
}
}

Slip19.Write a java program to accept a number from the user, if number is zero then throw user defined Exception
“Number is 0” otherwise calculate the sum of first and last digit of a given number (Use static keyword).

import java.util.*;
class ZeroException extends Exception
{
ZeroException()
{
super("Number is 0");
}
}
class Slip19
{
static int n;
public static void main(String args[])
{
int i,rem,sum=0;
try
{
Scanner sr=new Scanner(System.in);
n=sr.nextInt();
if(n==0)
{
throw new ZeroException();
}
else
{
rem=n%10;
sum=sum+rem;
if(n>9)
{
while(n>0)
{
rem=n%10;
n=n/10;
}
sum=sum+rem;
}
System.out.println("Sum is: "+sum);
}
}
catch(ZeroException e)
{
System.out.println(e);
}
}
}

Write a java program to display transpose of a given matrix.- Java Slip6

import java.io.*;
public class Matrix{

public static void main(String args[]){

//creating a matrix

int original[][]={{10,30,40},{20,40,30},{30,40,50}};

//creating another matrix to store transpose of a matrix

int transpose[][]=new int[3][3]; //3 rows and 3 columns

//Code to transpose a matrix

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

transpose[i][j]=original[j][i];

System.out.println("Printing Matrix without transpose:");

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(original[i][j]+" ");

System.out.println();//new line

System.out.println("Printing Matrix After Transpose:");

for(int i=0;i<3;i++){

for(int j=0;j<3;j++){

System.out.print(transpose[i][j]+" ");

System.out.println();//new line

}}
Output

C:\Program Files\Java\jdk1.7.0_80\bin>javac Matrix.java

C:\Program Files\Java\jdk1.7.0_80\bin>java Matrix

Printing Matrix without transpose:

10 30 40

20 40 30

30 40 50

Printing Matrix After Transpose:

10 20 30

30 40 40

40 30 50

C:\Program Files\Java\jdk1.7.0_80\bin>

Write a java program to display Label with text “Dr. D Y Patil College”, background color Red and font size 20 on the
frame.

import java.awt.*;

class Slip7 extends Frame

Slip7()

Label l=new Label("Dr. D Y Patil College");

Font f=new Font("Georgia",Font.BOLD,40);


l.setFont(f);

setForeground(Color.blue);

setBackground(Color.red);

add(l);

setLayout(new FlowLayout());

setSize(200,200);

setVisible(true);

public static void main(String arg[])

new Slip7();

Write a java program to accept details of ‘n’ cricket player (pid, pname, totalRuns, InningsPlayed, NotOuttimes).
Calculate the average of all the players. Display the details of player having maximum average. (Use Array of Object)

import java.io.*;

import java.util.Scanner;

class CricketPlayer1 {

int pid;

String pname;

int totalRuns;

int inningsPlayed;

int notOutTimes;

double average;
CricketPlayer1(int pid, String pname, int totalRuns, int inningsPlayed, int notOutTimes) {

this.pid = pid;

this.pname = pname;

this.totalRuns = totalRuns;

this.inningsPlayed = inningsPlayed;

this.notOutTimes = notOutTimes;

this.average = (double) totalRuns / (inningsPlayed - notOutTimes);

public class CricketPlayer {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of cricket players: ");

int n = scanner.nextInt();

CricketPlayer1[] players = new CricketPlayer1[n];

for (int i = 0; i < n; i++) {

System.out.println("\nEnter details for player " + (i + 1) + ":");

System.out.print("Player ID: ");

int pid = scanner.nextInt();

scanner.nextLine(); // Consume the newline

System.out.print("Player Name: ");

String pname = scanner.nextLine();

System.out.print("Total Runs: ");

int totalRuns = scanner.nextInt();

System.out.print("Innings Played: ");


int inningsPlayed = scanner.nextInt();

System.out.print("Not Out Times: ");

int notOutTimes = scanner.nextInt();

players[i] = new CricketPlayer1(pid, pname, totalRuns, inningsPlayed, notOutTimes);

double maxAverage = 0;

int maxAverageIndex = 0;

for (int i = 0; i < n; i++) {

if (players[i].average > maxAverage) {

maxAverage = players[i].average;

maxAverageIndex = i;

System.out.println("\nPlayer with the maximum average:");

System.out.println("Player ID: " + players[maxAverageIndex].pid);

System.out.println("Player Name: " + players[maxAverageIndex].pname);

System.out.println("Average: " + players[maxAverageIndex].average);

scanner.close();

}
Slip22. Define an Interface Shape with abstract method area(). Write a java program to calculate an area of Circle and
Sphere.(use final keyword)

interface shape
{
final static float pi=3.14f;
float area(float r);
}
class Circle implements shape
{
public float area(float r)
{
return(3.14f*r*r);
}
}
class sphere implements shape
{
public float area(float r)
{
return(2*3.14f*r*r);
}
}
class Main
{
public static void main(String args[])
{
Circle cir=new Circle();
sphere sp=new sphere();
shape s;
s=cir;
System.out.println("Area of Circle:"+s.area(3));
s=sp;
System.out.println("Area of Sphere:"+s.area(5));
}
}

Write a java program to display the files having extension .txt from a given directory.

import java.io.File;

public class ListTxtFiles {

public static void main(String[] args) {

// Specify the directory path where you want to search for .txt files

String directoryPath = "C:/Program Files/Java/jdk1.7.0_80/bin"; // Replace with your directory path

File directory = new File(directoryPath);

if (directory.exists() && directory.isDirectory()) {


File[] files = directory.listFiles();

if (files != null) {

System.out.println("List of .txt files in the directory:");

for (File file : files) {

if (file.isFile() && file.getName().toLowerCase().endsWith(".txt")) {

System.out.println(file.getName());

} else {

System.out.println("No files found in the directory.");

} else {

System.out.println("The specified directory does not exist or is not a directory.");

Output

C:\Program Files\Java\jdk1.7.0_80\bin>javac ListTxtFiles.java

C:\Program Files\Java\jdk1.7.0_80\bin>java ListTxtFiles

List of .txt files in the directory:

a.txt

b.txt
Write a java Program to display following Pattern:

01

010

1010

public class PatternDisplay {

public static void main(String[] args) {

int n = 4; // Number of rows in the pattern

for (int i = 0; i < n; i++) {

int numToPrint = (i % 2 == 0) ? 1 : 0;

for (int j = 0; j <= i; j++) {

System.out.print(numToPrint + " ");

numToPrint = 1 - numToPrint;

System.out.println();

Output:-

C:\Program Files\Java\jdk-11.0.17\bin>javac PatternDisplay.java

C:\Program Files\Java\jdk-11.0.17\bin>java PatternDisplay

01

101

0101

Write a java program to validate PAN number and Mobile Number. If it is invalid then throw user defined Exception
“Invalid Data”, otherwise display it.

class InvalidDataException extends Exception {

public InvalidDataException(String message) {

super(message);
}

public class DataValidator {

public static void main(String[] args) {

try {

String panNumber = "ABC12"; // Replace with the PAN number to validate

String mobileNumber = "1234567890"; // Replace with the mobile number to validate

validatePAN(panNumber);

validateMobileNumber(mobileNumber);

System.out.println("Valid PAN Number: " + panNumber);

System.out.println("Valid Mobile Number: " + mobileNumber);

} catch (InvalidDataException e) {

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

public static void validatePAN(String pan) throws InvalidDataException {

if (pan.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {

// PAN is valid

} else {

throw new InvalidDataException("Invalid PAN Number");

public static void validateMobileNumber(String mobileNumber) throws InvalidDataException {

if (mobileNumber.matches("[0-9]{10}")) {

// Mobile number is valid

} else {
throw new InvalidDataException("Invalid Mobile Number");

OutPut

C:\Program Files\Java\jdk-11.0.17\bin>javac DataValidator.java

C:\Program Files\Java\jdk-11.0.17\bin>java DataValidator

Error: Invalid PAN Number

Write a java program to count the frequency of each character in a given string.

import java.util.HashMap;

import java.util.Map;

import java.io.*;

public class CharacterFrequencyCounter {

public static void main(String[] args) {

String inputString = "Hello, World!";

// Create a HashMap to store character frequencies

Map<Character, Integer> charFrequencyMap = new HashMap<>();

// Iterate through the characters in the string

for (char c : inputString.toCharArray()) {

if (charFrequencyMap.containsKey(c)) {

// Character already exists in the map, increment the count

charFrequencyMap.put(c, charFrequencyMap.get(c) + 1);

} else {

// Character does not exist in the map, add it with a count of 1

charFrequencyMap.put(c, 1);

}
}

// Print the character frequencies

for (Map.Entry<Character, Integer> entry : charFrequencyMap.entrySet()) {

System.out.println("Character: " + entry.getKey() + ", Frequency: " + entry.getValue());

Output

C:\Program Files\Java\jdk-11.0.17\bin>javac CharacterFrequencyCounter.java

C:\Program Files\Java\jdk-11.0.17\bin>java CharacterFrequencyCounter

Character: , Frequency: 1

Character: !, Frequency: 1

Character: r, Frequency: 1

Character: d, Frequency: 1

Character: e, Frequency: 1

Character: W, Frequency: 1

Character: H, Frequency: 1

Character: l, Frequency: 3

Character: ,, Frequency: 1

Character: o, Frequency: 2Write a java program to calculate Total amount and Interest amount Using textbox,label and
3 button for Calculate Button ,Clear Button ,Close Button.

import java.awt.*;

import java.awt.event.*;

public class InterestCalculatorAWT extends Frame {

private TextField p, r, time1, total, interestAmount;


private Button calculate, clear, close;

public InterestCalculatorAWT() {

setTitle("Interest Calculator");

setSize(400, 200);

setLayout(null);

Label l1 = new Label("Principal Amount:");

l1.setBounds(20, 30, 120, 20);

add(l1);

p = new TextField();

p.setBounds(160, 30, 200, 20);

add(p);

Label r1 = new Label("Rate of Interest (%):");

r1.setBounds(20, 60, 120, 20);

add(r1);

r = new TextField();

r.setBounds(160, 60, 200, 20);

add(r);

Label l3 = new Label("Time (years):");

l3.setBounds(20, 90, 120, 20);

add(l3);

time1 = new TextField();

time1.setBounds(160, 90, 200, 20);

add(time1);
calculate = new Button("Calculate");

calculate.setBounds(20, 120, 100, 30);

add(calculate);

clear = new Button("Clear");

clear.setBounds(140, 120, 100, 30);

add(clear);

close = new Button("Close");

close.setBounds(260, 120, 100, 30);

add(close);

total = new TextField();

total.setBounds(20, 160, 340, 20);

total.setEditable(false);

add(total);

interestAmount = new TextField();

interestAmount.setBounds(20, 190, 340, 20);

interestAmount.setEditable(false);

add(interestAmount);

calculate.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

calculate();

});

clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

clear();

});

close.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

System.exit(0);

});

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

});

setVisible(true);

private void calculate() {

try {

double principal = Double.parseDouble(p.getText());

double rate = Double.parseDouble(r.getText());

double time = Double.parseDouble(time1.getText());

double interest = (principal * rate * time) / 100;

double totalAmount = principal + interest;

total.setText("Total Amount: " + totalAmount);


interestAmount.setText("Interest Amount: " + interest);

} catch (NumberFormatException e) {

// Handle invalid input

total.setText("Invalid input");

interestAmount.setText("Invalid input");

private void clear() {

p.setText("");

r.setText("");

time1.setText("");

total.setText("");

interestAmount.setText("");

public static void main(String[] args) {

new InterestCalculatorAWT();

Write a menu driven java program using command line arguments for the following:

1. Addition

2. Subtraction

3. Multiplication

4. Division.

import java.io.*;

public class CommandLineCalculator {

public static void main(String[] args) {

if (args.length != 3) {
System.out.println("CommandLine Argument");

return;

String operation = args[0];

double num1 = Double.parseDouble(args[1]);

double num2 = Double.parseDouble(args[2]);

double result = 0;

switch (operation) {

case "1":

result = num1 + num2;

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

break;

case "2":

result = num1 - num2;

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

break;

case "3":

result = num1 * num2;

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

break;

case "4":

if (num2 == 0) {

System.out.println("Error: Division by zero is not allowed.");

} else {

result = num1 / num2;

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

}
break;

default:

System.out.println("Invalid operation. Please choose 1 for Addition, 2 for Subtraction, 3 for Multiplication, or 4
for Division.");

Output-

C:\Program Files\Java\jdk1.7.0_80\bin>javac CommandLineCalculator.java

C:\Program Files\Java\jdk1.7.0_80\bin>java CommandLineCalculator 1 4 5

Addition Result: 9.0

C:\Program Files\Java\jdk1.7.0_80\bin>java CommandLineCalculator 2 4 2

Subtraction Result: 2.0

C:\Program Files\Java\jdk1.7.0_80\bin>

Write an applet application to display Table lamp.The color of lamp should get change randomly

import java.applet.*;

import java.awt.*;

public class Lamp extends java.applet.Applet {

public void init() {

resize(300,300);
}

public void paint(Graphics g) {

// the platform

g.fillRect(0,250,290,290);

// the base of the lamp

g.drawLine(125,250,125,160);

g.drawLine(175,250,175,160);

// the lamp shade; two arcs

g.drawArc(85,157,130,50,-65,312);

g.drawArc(85,87,130,50,62,58);

g.drawLine(85,177,119,89);

g.drawLine(215,177,181,89);

// pattern on the shade

g.fillArc(78,120,40,40,63,-174);

g.fillOval(120,96,40,40);

g.fillArc(173,100,40,40,110,180);

Lamp.html

<html>

<body>

<applet code="Lamp.class" width="300" height="300">

</applet>

</body>

</html>
Output-

C:\Program Files\Java\jdk1.7.0_80\bin>javac Lamp.java

C:\Program Files\Java\jdk1.7.0_80\bin>appletviewer Lamp.html

import java.io.*;

public class ReverseStringArray {

public static void main(String[] args) {

// Sample array of strings

String[] stringArray = {"Hello", "World"};

// Iterate through the array and reverse each string

for (String originalString : stringArray) {

String reversedString = new StringBuilder(originalString).reverse().toString();

System.out.println("Original: " + originalString + " Reversed: " + reversedString);

C:\Program Files\Java\jdk-11.0.17\bin>javac ReverseStringArray.java

C:\Program Files\Java\jdk-11.0.17\bin>java ReverseStringArray

Original: Hello Reversed: olleH

Original: World Reversed: dlroW


C:\Program Files\Java\jdk-11.0.17\bin>
Write a java program to display multiplication table of a given number into the List box by clicking on button.

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MultiplicationTableApp extends JFrame {

private JTextField numberField;

private JButton displayButton;

private JList<String> tableList;

public MultiplicationTableApp() {

setTitle("Multiplication Table");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(300, 400);

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(3, 1));


numberField = new JTextField();

displayButton = new JButton("Display");

DefaultListModel<String> tableModel = new DefaultListModel<>();

tableList = new JList<>(tableModel);

displayButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

tableModel.clear();

String numberInput = numberField.getText();

try {

int number = Integer.parseInt(numberInput);

for (int i = 1; i <= 10; i++) {

int result = number * i;

tableModel.addElement(number + " x " + i + " = " + result);

} catch (NumberFormatException ex) {

tableModel.addElement("Invalid input. Please enter a valid number.");

});

panel.add(numberField);

panel.add(displayButton);

panel.add(new JScrollPane(tableList));

add(panel);

}
public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

MultiplicationTableApp app = new MultiplicationTableApp();

app.setVisible(true);

});

C:\Program Files\Java\jdk-11.0.17\bin>javac MultiplicationTableApp.java

C:\Program Files\Java\jdk-11.0.17\bin>java MultiplicationTableAp

Write a java program to accept ‘n’ integers from the user & store them in an ArrayList collection. Display the elements of
ArrayList collection in reverse order.

import java.io.*;

import java.util.ArrayList;

import java.util.Scanner;

public class ReverseArrayList {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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


System.out.print("Enter the number of integers (n): ");

int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");

for (int i = 0; i < n; i++) {

int num = scanner.nextInt();

numberList.add(num);

System.out.println("Elements in reverse order:");

for (int i = numberList.size() - 1; i >= 0; i--) {

System.out.println(numberList.get(i));

scanner.close();

C:\Program Files\Java\jdk-11.0.17\bin>javac ReverseArrayList.java

C:\Program Files\Java\jdk-11.0.17\bin>java ReverseArrayList

Enter the number of integers (n): 3

Enter 3 integers:

123

124

125

Elements in reverse order:

125
124

123

Write a Java program to calculate power of a number using recursion.

import java.util.Scanner;

import java.io.*;

public class powernum {

public static int power(int base, int exp){

if (exp !=0){

return (base * power(base, exp-1));

}else {

return 1;

public static void main(String args[]){

Scanner sc = new Scanner(System.in);

System.out.println("Enter the base number :");

int base = sc.nextInt();

System.out.println("Enter the exponent number :");

int exp = sc.nextInt();

System.out.println("Output : "+power(base, exp));

}
}

C:\Program Files\Java\jdk1.7.0_80\bin>javac powernum.java

C:\Program Files\Java\jdk1.7.0_80\bin>java powernum

Enter the base number : 7

Enter the exponent number : 2

Output : 49

Slip24. Write a Java Program to accept the details of Employee(Eno, EName,Sal) from the user and display it on the
next Frame. (Use AWT)

import java.awt.*;
import java.awt.event.*;
class EmployeeDetails implements ActionListener
{
Frame f;
Label empno,empname,sal,basic,hr;
TextField tempno,tempname,tsal,tbasic,thr;
Button next;

EmployeeDetails()
{
f=new Frame("\t Employee Details:");
empno=new Label("\t Employee Id:");
empname=new Label("\t Employee Name:");
sal=new Label("\t Employee Sal:");
basic=new Label("\t Employee Basic:");
hr=new Label("\t Employee Hr:");
tempno=new TextField(20);
tempname=new TextField(20);
tsal=new TextField(20);
tbasic=new TextField(20);
thr=new TextField(20);
next=new Button("Next");
f.add(empno);
f.add(tempno);
f.add(empname);
f.add(tempname);
f.add(sal);
f.add(tsal);
f.add(basic);
f.add(tbasic);
f.add(hr);
f.add(thr);
f.add(next);
next.addActionListener(this);
f.setLayout(new FlowLayout());
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String empno,empname,sal,basic,hr;
empno=tempno.getText();
empname=tempname.getText();
sal=tsal.getText();
basic=tbasic.getText();
hr=thr.getText(); ;
f.setVisible(false);
new FrameDetails(empno,empname,sal,basic,hr);
}
}
class FrameDetails extends Frame
{
Frame f;
Label empno,empname,sal,basic,hr;
TextField tempno,tempname,tsal,tbasic,thr;
FrameDetails(String no,String name,String s,String add,String d)
{
f= new Frame("\t Payment Details:");
empno=new Label("\t E-ID:");
empname=new Label("\t E-Name:");
sal=new Label("\t Salary:");
basic=new Label("\t Basic:");
hr=new Label("\t Hr:");
tempno= new TextField(20);
tempname=new TextField(20);
tsal=new TextField(20);
tbasic=new TextField(20);
thr=new TextField(20);
f.add(empno);
f.add(tempno);
f.add(empname);
f.add(tempname);
f.add(sal);
f.add(tsal);
f.add(basic);
f.add(tbasic);
f.add(hr);
f.add(thr);
tempno.setText(no);
tempname.setText(name);
tsal.setText(s);
tbasic.setText(add);
thr.setText(d);
f.setLayout(new FlowLayout());
f.setSize(400,400);
f.setVisible(true);
}
}
class salary
{
public static void main(String args[])
{
new EmployeeDetails();
}
}

Write a java program to calculate sum of digits of a given number using recursion.

import java.io.*;

public class SumOfDigits {

public static void main(String[] args) {

int number = 123; // Change this to the number you want to calculate the sum for

int sum = calculateSumOfDigits(number);

System.out.println("The sum of digits in " + number + " is: " + sum);

public static int calculateSumOfDigits(int num) {

if (num == 0) {

return 0; // Base case: If the number is 0, the sum is 0

} else {

// Calculate the sum of digits for the remaining part of the number

int lastDigit = num % 10; // Get the last digit

int remainingNumber = num / 10; // Remove the last digit

return lastDigit + calculateSumOfDigits(remainingNumber); // Recursive call

}
}

Write a java program to accept n employee names from user. Sort them in ascending

order and Display them.(Use array of object and Static keyword)

import java.io.*;

import java.util.Scanner;

public class EmployeeSort

static class Employee

String name;

Employee(String name)

this.name = name;

static void sortEmployeesByName(Employee[] employees)

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

for (int j = i + 1; j < employees.length; j++)

{
if (employees[i].name.compareTo(employees[j].name) > 0)

Employee temp = employees[i];

employees[i] = employees[j];

employees[j] = temp;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of employees (n): ");

int n = scanner.nextInt();

scanner.nextLine(); // Consume the newline character

Employee[] employees = new Employee[n];

// Accept employee names from the user

for (int i = 0; i < n; i++) {

System.out.print("Enter the name of employee " + (i + 1) + ": ");

String name = scanner.nextLine();

employees[i] = new Employee(name);

// Sort the employee names in ascending order using a static method

Employee.sortEmployeesByName(employees);

// Display the sorted employee names


System.out.println("Sorted Employee Names:");

for (int i = 0; i < n; i++) {

System.out.println(employees[i].name);

scanner.close();

Write a java Program to accept ‘n’ no’s through command line and store only Armstrong no’s into the array and display
that array.

import java.util.ArrayList;

import java.io.*;

public class ArmstrongNumbers {

public static void main(String[] args) {

if (args.length == 0) {

System.out.println("Please provide some numbers as command-line arguments.");

return;

int n = args.length;

int[] numbers = new int[n];

for (int i = 0; i < n; i++) {

try {

numbers[i] = Integer.parseInt(args[i]);

} catch (NumberFormatException e) {

System.out.println("Invalid input: " + args[i] + " is not a valid number.");


return;

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

for (int number : numbers) {

if (isArmstrongNumber(number)) {

armstrongNumbers.add(number);

if (armstrongNumbers.isEmpty()) {

System.out.println("No Armstrong numbers found in the provided input.");

} else {

System.out.println("Armstrong numbers in the input:");

for (int armstrongNumber : armstrongNumbers) {

System.out.println(armstrongNumber);

public static boolean isArmstrongNumber(int number) {

int originalNumber, remainder, result = 0;

originalNumber = number;

while (originalNumber != 0) {

remainder = originalNumber % 10;

result += Math.pow(remainder, 3);

originalNumber /= 10;

}
return result == number;

Define a class Product (pid, pname, price, qty). Write a function to accept the product details, display it and calculate
total amount. (use array of Objects)

import java.util.Scanner;

import java.io.*;

class Product {

int pid;

String pname;

double price;

int qty;

public Product(int pid, String pname, double price, int qty) {

this.pid = pid;

this.pname = pname;

this.price = price;

this.qty = qty;

public double calculateTotal() {

return price * qty;

}
public void displayProduct() {

System.out.println("Product ID: " + pid);

System.out.println("Product Name: " + pname);

System.out.println("Price: $" + price);

System.out.println("Quantity: " + qty);

public class ProductDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of products: ");

int numProducts = scanner.nextInt();

Product[] products = new Product[numProducts];

for (int i = 0; i < numProducts; i++) {

System.out.println("Enter details for product #" + (i + 1));

System.out.print("Product ID: ");

int pid = scanner.nextInt();

scanner.nextLine(); // Consume newline

System.out.print("Product Name: ");

String pname = scanner.nextLine();

System.out.print("Price: $");

double price = scanner.nextDouble();

System.out.print("Quantity: ");

int qty = scanner.nextInt();

products[i] = new Product(pid, pname, price, qty);

}
System.out.println("Product Details:");

double totalAmount = 0;

for (Product product : products) {

product.displayProduct();

double productTotal = product.calculateTotal();

System.out.println("Total Amount for this product: $" + productTotal);

totalAmount += productTotal;

System.out.println();

System.out.println("Total Amount for all products: $" + totalAmount);

Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method Overloading)

import java.util.Scanner;

import java.io.*;

public class AreaCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("1. Calculate the area of a circle");

System.out.println("2. Calculate the area of a triangle");

System.out.println("3. Calculate the area of a rectangle");


System.out.print("Enter your choice (1/2/3): ");

int choice = scanner.nextInt();

switch (choice) {

case 1:

System.out.print("Enter the radius of the circle: ");

double radius = scanner.nextDouble();

System.out.println("Area of the circle: " + calculateArea(radius));

break;

case 2:

System.out.print("Enter the base of the triangle: ");

double base = scanner.nextDouble();

System.out.print("Enter the height of the triangle: ");

double height = scanner.nextDouble();

System.out.println("Area of the triangle: " + calculateArea(base, height));

break;

case 3:

System.out.print("Enter the length of the rectangle: ");

double length = scanner.nextDouble();

System.out.print("Enter the width of the rectangle: ");

double width = scanner.nextDouble();

System.out.println("Area of the rectangle: " + calculateArea(length, width));

break;

default:

System.out.println("Invalid choice");

}
public static double calculateArea(double radius) {

return Math.PI * radius * radius;

public static double calculateArea(double base, double height) {

return 0.5 * base * height;

public static double calculateArea(double length, double width) {

return length * width;

Slip13.Write a java program to copy the contents of one file into the another file, while copying change the case of
alphabets and replace all the digits by ‘*’ in target file .

import java.util.*;
import java.io.*;
class Slip13
{
public static void main(String a[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name to copy");
String f1=br.readLine();
System.out.println("Enter destination file");
String f2=br.readLine();
FileReader fr=new FileReader(f1);
FileWriter fw=new FileWriter(f2);
int ch;
while((ch=fr.read() ) != -1)
{
char ch1=(char)ch;
if(Character.isUpperCase(ch1))
{
ch1=Character.toLowerCase(ch1);
fw.write(ch1);
}
else if(Character.isLowerCase(ch1))
{
ch1=Character.toUpperCase(ch1);
fw.write(ch1);
}
else if(Character.isDigit(ch1))
{
ch1='*';
fw.write(ch1);
}
else if(Character.isSpace(ch1))
{
fw.write(ch1);
}
}
fr.close();
fw.close();
}
}

Create an Applet that displays the x and y position of the cursor movement

using Mouse and Keyboard. (Use appropriate listener)

import java.io.*;

import java.applet.Applet;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

public class MouseKeyboardPositionApplet extends Applet {

private int mouseX = 0;

private int mouseY = 0;

public void init() {

addMouseListener(new MyMouseListener());

addKeyListener(new MyKeyListener());
setFocusable(true);

requestFocus();

public void paint(java.awt.Graphics g) {

g.drawString("Mouse Position: (" + mouseX + ", " + mouseY + ")", 10, 20);

class MyMouseListener extends MouseAdapter {

public void mouseMoved(MouseEvent e) {

mouseX = e.getX();

mouseY = e.getY();

repaint();

class MyKeyListener extends KeyAdapter {

public void keyPressed(KeyEvent e) {

if (e.getKeyCode() == KeyEvent.VK_UP) {

mouseY--;

} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {

mouseY++;

} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {

mouseX--;

} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

mouseX++;

repaint();

}
}

Write a java program using AWT to create a Frame with title “TYBBACA”, background color RED. If user clicks on close
button then frame should close.

import java.awt.*;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class RedFrame {

public static void main(String[] args) {

Frame frame = new Frame("TYBBACA");

frame.setBackground(Color.RED);

// Add a window listener to close the frame when the close button is clicked

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

});

frame.setSize(400, 400);

frame.setVisible(true);

}
}

Construct a Linked List containing name: CPP, Java, Python and PHP. Then extend your java program to do the
following:

Display the contents of the List using an Iterator

Display the contents of the List in reverse order using a ListIterator.

import java.util.LinkedList;

import java.util.List;

import java.util.ListIterator;

import java.util.Iterator;

public class LinkedListDemo {

public static void main(String[] args) {

// Create a linked list of names

List<String> names = new LinkedList<>();

names.add("CPP");

names.add("Java");

names.add("Python");

names.add("PHP");

// Display the contents of the list using an Iterator

System.out.println("Contents of the List using an Iterator:");

Iterator<String> iterator = names.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());

}
// Display the contents of the list in reverse order using a ListIterator

System.out.println("\nContents of the List in Reverse Order using a ListIterator:");

ListIterator<String> listIterator = names.listIterator(names.size());

while (listIterator.hasPrevious()) {

System.out.println(listIterator.previous());

Slip 9. Write a java program to display the contents of a file in reverse order.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main
{
public static void main(String args[])throws Exception,IOException
{
Scanner scanner=new Scanner(new File("a.txt")).useDelimiter("\\z");
String contents=scanner.next();
contents=new StringBuffer(contents).reverse().toString();
System.out.println("Reversed String:"+contents);
FileWriter fstream=new FileWriter("a.txt");
BufferedWriter out=new BufferedWriter(fstream);
out.write(contents);
out.close();
}
}

Create a hashtable containing city name & STD code. Display the details of the hashtable. Also search for a specific city
and display STD code of that city.

import java.util.Hashtable;
import java.util.Scanner;

import java.io.*;

public class CitySTDHashtable {

public static void main(String[] args) {

Hashtable<String, String> citySTDTable = new Hashtable<>();

// Populate the Hashtable with city names and STD codes

citySTDTable.put("New York", "212");

citySTDTable.put("Los Angeles", "213");

citySTDTable.put("Chicago", "312");

citySTDTable.put("San Francisco", "415");

citySTDTable.put("Boston", "617");

// Display the details of the Hashtable

System.out.println("City STD Codes:");

for (String city : citySTDTable.keySet()) {

System.out.println(city + " - STD Code: " + citySTDTable.get(city));

// Search for a specific city and display its STD code

Scanner scanner = new Scanner(System.in);

System.out.print("\nEnter a city name to search for STD code: ");

String searchCity = scanner.nextLine();

String stdCode = citySTDTable.get(searchCity);

if (stdCode != null) {

System.out.println("STD Code for " + searchCity + ": " + stdCode);

} else {

System.out.println("City not found in the Hashtable.");

}
}

Write a Java program to calculate factorial of a number using recursion.

import java.util.Scanner;

public class FactorialCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a non-negative integer to calculate its factorial: ");

int n = scanner.nextInt();

if (n < 0) {

System.out.println("Factorial is not defined for negative numbers.");

} else {

long factorial = calculateFactorial(n);

System.out.println("Factorial of " + n + " is: " + factorial);

public static long calculateFactorial(int n) {

if (n == 0 || n == 1) {

return 1;

} else {

return n * calculateFactorial(n - 1);


}

Write a java program for the following:

To create a file.

To rename a file.

To delete a file.

To display path of a file.

import java.io.File;

import java.io.IOException;

public class FileOperations {

public static void main(String[] args) {

// Create a file

createFile("sample.txt");

// Rename a file

renameFile("sample.txt", "newSample.txt");

// Display the path of a file

displayFilePath("newSample.txt");

// Delete a file

deleteFile("newSample.txt");

}
public static void createFile(String fileName) {

File file = new File(fileName);

try {

if (file.createNewFile()) {

System.out.println("File created: " + file.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) {

System.out.println("An error occurred while creating the file.");

e.printStackTrace();

public static void renameFile(String oldFileName, String newFileName) {

File oldFile = new File(oldFileName);

File newFile = new File(newFileName);

if (oldFile.renameTo(newFile)) {

System.out.println("File renamed to: " + newFileName);

} else {

System.out.println("Unable to rename the file.");

public static void displayFilePath(String fileName) {

File file = new File(fileName);

System.out.println("File path: " + file.getAbsolutePath());


}

public static void deleteFile(String fileName) {

File file = new File(fileName);

if (file.delete()) {

System.out.println("File deleted: " + fileName);

} else {

System.out.println("Unable to delete the file.");

Write a java program to check whether given file is hidden or not. If not then display its path, otherwise display
appropriate message.

import java.io.File;

public class FileHiddenCheck {

public static void main(String[] args) {

String filePath = "path_to_your_file_here"; // Replace with the file path you want to check

File file = new File(filePath);


if (file.exists()) {

if (file.isHidden()) {

System.out.println("The file is hidden.");

} else {

System.out.println("File path: " + file.getAbsolutePath());

} else {

System.out.println("The specified file does not exist.");

Write a java program to design following Frame using Swing.

import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class SwingMenuExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Menu Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 300);

// Create a menu bar

JMenuBar menuBar = new JMenuBar();

// Create "File" menu


JMenu fileMenu = new JMenu("File");

JMenuItem exitMenuItem = new JMenuItem("Exit");

exitMenuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

System.exit(0);

});

fileMenu.add(exitMenuItem);

// Create "Edit" menu with submenus

JMenu editMenu = new JMenu("Edit");

JMenuItem undoMenuItem = new JMenuItem("Undo");

JMenuItem redoMenuItem = new JMenuItem("Redo");

JMenuItem cutMenuItem = new JMenuItem("Cut");

JMenuItem copyMenuItem = new JMenuItem("Copy");

JMenuItem pasteMenuItem = new JMenuItem("Paste");

editMenu.add(undoMenuItem);

editMenu.add(redoMenuItem);

editMenu.addSeparator(); // Separator

editMenu.add(cutMenuItem);

editMenu.add(copyMenuItem);

editMenu.add(pasteMenuItem);

// Create "Search" menu

JMenu searchMenu = new JMenu("Search");

// Add menus to the menu bar

menuBar.add(fileMenu);

menuBar.add(editMenu);

menuBar.add(searchMenu);
frame.setJMenuBar(menuBar);

frame.setVisible(true);

Write a java program to count number of digits, spaces and characters from a file.

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class FileCharacterCount {

public static void main(String[] args) {

String fileName = "your_file.txt"; // Replace with the actual file path

int digitCount = 0;

int spaceCount = 0;

int characterCount = 0;

try (BufferedReader reader = new BufferedReader(new FileReader(fileName)) {

int c;

while ((c = reader.read()) != -1) {

char ch = (char) c;

if (Character.isDigit(ch)) {

digitCount++;

} else if (Character.isWhitespace(ch)) {
spaceCount++;

characterCount++;

} catch (IOException e) {

System.err.println("An error occurred while reading the file.");

e.printStackTrace();

System.out.println("Digits: " + digitCount);

System.out.println("Spaces: " + spaceCount);

System.out.println("Characters: " + characterCount);

Create a package TYBBACA with two classes as class Student (Rno, SName, Per) with a method disp() to display
details of N Students and class Teacher (TID, TName, Subject) with a method disp() to display the details of teacher
who is teaching Java subject. (Make use of finalize() method and array of Object)

Student.java

package bca;

public class Student

protected int Rno;

protected String SName;

protected double Per;

public Student() { }
public Student(int R, String S1,double P)

{ Rno=R;

SName=S1;

Per=P;

public void display()

System.out.println(Rno);

System.out.println(SName);

System.out.println(Per);

protected void finalize()

System.out.println("Student Details...");

}}

Teacher.java

package bca;

public class Teacher

private int TID;

private String TName;

private String Subject;

public Teacher(){ }

public Teacher(int T, String TN, String Sub) {

TID = T;

TName = TN;

Subject = Sub;
}

public void display()

System.out.println(TID);

System.out.println(TName);

System.out.println(Subject);

protected void finalize()

{System.out.println("Teacher Details..."); }

Test.java

import bca.*;

public class Test

public static void main(String args[])

Student[] students = new Student[3];

students[0] = new Student(1, "Alice", 90.5);

students[1] = new Student(2, "Bob", 85.2);

students[2] = new Student(3, "Charlie", 78.0);

System.out.println("Student Details...");

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

students[i].display();
System.out.println("Teacher Details...");

Teacher[] teachers = new Teacher[2];

teachers[0] = new Teacher(101, "Mr. Smith", "Java");

teachers[1] = new Teacher(102, "Ms. Johnson", "Math");

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

teachers[i].display();

/*

C:\TYBBACA\bca>javac Teacher.java

C:\TYBBACA\bca>javac Student.java

C:\TYBBACA\bca>cd..

C:\TYBBACA>javac Test.java

C:\TYBBACA>java Test

Student Details...

Alice

90.5

Bob

85.2

Charlie

78.0

Teacher Details...
101

Mr. Smith

Java

102

Ms. Johnson

Math

*/

C:\TYBBACA>

Write a java program to check whether given string is palindrome or not

import java.util.Scanner;

public class PalindromeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string to check for palindrome: ");

String input = scanner.nextLine();

if (isPalindrome(input)) {

System.out.println("The entered string is a palindrome.");

} else {

System.out.println("The entered string is not a palindrome.");

public static boolean isPalindrome(String str) {

str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to


lowercase

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;

right--;

return true;

Create a package named Series having three different classes to print series:

Fibonacci series

Cube of numbers

Square of numbers

Write a java program to generate ‘n’ terms of the above series.

Fibonacci.java

package Series;

public class Fibonacci {

public static void generateFibonacciSeries(int n) {

int a = 0, b = 1;

System.out.print("Fibonacci Series (" + n + " terms): ");


for (int i = 1; i <= n; i++) {

System.out.print(a + " ");

int sum = a + b;

a = b;

b = sum;

CubeOfNumbers.java

package Series;

public class CubeOfNumbers {

public static void generateCubeSeries(int n) {

System.out.print("Cube of Numbers (" + n + " terms): ");

for (int i = 1; i <= n; i++) {

int cube = i * i * i;

System.out.print(cube + " ");

SquareOfNumbers.java

package Series;

public class SquareOfNumbers {

public static void generateSquareSeries(int n) {

System.out.print("Square of Numbers (" + n + " terms): ");

for (int i = 1; i <= n; i++) {

int square = i * i;

System.out.print(square + " ");

}
}

SeriesMain.java

import Series.*;

public class SeriesMain {

public static void main(String[] args) {

int n = 10; // Number of terms

Fibonacci.generateFibonacciSeries(n);

System.out.println();

CubeOfNumbers.generateCubeSeries(n);

System.out.println();

SquareOfNumbers.generateSquareSeries(n);

System.out.println();

Write a java program to display ASCII values of the characters from a file.

import java.io.FileInputStream;

import java.io.IOException;

public class FileASCIIValues {

public static void main(String[] args) {


String fileName = "your_file.txt"; // Replace with the actual file path

try (FileInputStream fileInputStream = new FileInputStream(fileName)) {

int character;

while ((character = fileInputStream.read()) != -1) {

System.out.println("Character: " + (char) character + " | ASCII Value: " + character);

} catch (IOException e) {

System.err.println("An error occurred while reading the file.");

e.printStackTrace();

Slip10.Write an Applet application in Java for designing Temple.

Slip10.java

import java.applet.Applet;
import java.awt.*;
public class Slip10 extends Applet
{
public void paint(Graphics g)
{
g.drawRect(100,150,90,120);
g.drawRect(130,230,20,40);
g.drawLine(150,100,100,150);
g.drawLine(150,100,190,150);
g.drawLine(150,50,150,100);
g.drawRect(150,50,20,20);
}
}

Temple.html

<Applet code=Slip10.class width=250 height=250></Applet>


Write a java program to accept a number from user, If it is greater than 1000 then throw user defined exception “Number
is out of Range” otherwise display the factors of that number. (Use static keyword)

class NumberOutOfRangeException extends Exception {

public NumberOutOfRangeException(String message) {

super(message);

public class FactorsCalculator {

public static void main(String[] args) {

try {

int number = 1200; // Replace with the number you want to check

if (number > 1000) {

throw new NumberOutOfRangeException("Number is out of Range");

} else {

System.out.println("Factors of " + number + ":");

displayFactors(number);

} catch (NumberOutOfRangeException e) {

System.err.println(e.getMessage());

public static void displayFactors(int number) {

for (int i = 1; i <= number; i++) {

if (number % i == 0) {

System.out.println(i);
}

Write a java program to accept directory name in TextField and display list of files and subdirectories in List Control from
that directory by clicking on Button.

import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.File;

public class DirectoryLister extends JFrame {

private JTextField directoryField;

private JButton listButton;

private JList<String> fileList;

public DirectoryLister() {

setTitle("Directory Lister");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

directoryField = new JTextField();

listButton = new JButton("List Directory");

fileList = new JList<>();

listButton.addActionListener(new ActionListener() {
@Override

public void actionPerformed(ActionEvent e) {

listDirectoryContents();

});

JPanel panel = new JPanel();

panel.add(new JLabel("Directory: "));

panel.add(directoryField);

panel.add(listButton);

JScrollPane scrollPane = new JScrollPane(fileList);

add(panel, "North");

add(scrollPane, "Center");

private void listDirectoryContents() {

String directoryPath = directoryField.getText();

File directory = new File(directoryPath);

if (directory.exists() && directory.isDirectory()) {

String[] contents = directory.list();

fileList.setListData(contents);

} else {

fileList.setListData(new String[] { "Directory not found." });

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {

public void run() {

DirectoryLister directoryLister = new DirectoryLister();

directoryLister.setVisible(true);

});

Write a java program to count the number of integers from a given list. (Use Command line arguments).

public class CountIntegers {

public static void main(String[] args) {

if (args.length == 0) {

System.out.println("No command line arguments provided. Please provide a list of numbers.");

return;

int count = 0;

for (String arg : args) {

try {

int number = Integer.parseInt(arg);

count++;

} catch (NumberFormatException e) {
// Ignore non-integer arguments

System.out.println("Number of integers in the list: " + count);

Write a java Program to accept the details of 5 employees (Eno, Ename, Salary) and display it onto the JTable.

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

public class EmployeeDetailsApp {

public static void main(String[] args) {

JFrame frame = new JFrame("Employee Details");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 300);

// Create a table model with column names

DefaultTableModel tableModel = new DefaultTableModel();

tableModel.addColumn("Employee Number");

tableModel.addColumn("Employee Name");

tableModel.addColumn("Salary");

// Create a JTable with the table model

JTable employeeTable = new JTable(tableModel);


// Create a scroll pane to host the JTable

JScrollPane scrollPane = new JScrollPane(employeeTable);

frame.add(scrollPane);

// Add employee details to the JTable

for (int i = 1; i <= 5; i++) {

String eno = JOptionPane.showInputDialog("Enter Employee Number " + i);

String ename = JOptionPane.showInputDialog("Enter Employee Name " + i);

String salary = JOptionPane.showInputDialog("Enter Salary for Employee " + i);

tableModel.addRow(new String[]{eno, ename, salary});

frame.setVisible(true);

Write a java program to check whether given candidate is eligible for voting or not. Handle user defined as well as
system definedException.

import java.util.InputMismatchException;

import java.util.Scanner;

class AgeBelow18Exception extends Exception {

public AgeBelow18Exception(String message) {

super(message);

}
}

public class VotingEligibility {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

System.out.print("Enter the candidate's age: ");

int age = scanner.nextInt();

if (age < 18) {

throw new AgeBelow18Exception("Candidate is not eligible for voting as age is below 18.");

} else {

System.out.println("Candidate is eligible for voting.");

} catch (AgeBelow18Exception e) {

System.err.println(e.getMessage());

} catch (InputMismatchException e) {

System.err.println("Invalid input. Please enter a valid age as a numeric value.");

Write a java program using Applet for bouncing ball. Ball should change its color for each bounce.

import java.applet.*;

import java.awt.*;
public class BouncingBallApplet extends Applet implements Runnable {

private int x, y; // Current position of the ball

private int xSpeed, ySpeed; // Speed of the ball

private Color[] colors = { Color.RED, Color.GREEN, Color.BLUE, Color.ORANGE, Color.MAGENTA };

private int colorIndex = 0;

public void init() {

x = 100;

y = 100;

xSpeed = 3;

ySpeed = 2;

public void start() {

Thread t = new Thread(this);

t.start();

public void run() {

while (true) {

if (x < 0 || x > getWidth() - 20) {

xSpeed = -xSpeed; // Reverse direction when hitting the left or right edge

changeColor();

if (y < 0 || y > getHeight() - 20) {

ySpeed = -ySpeed; // Reverse direction when hitting the top or bottom edge

changeColor();

x += xSpeed;

y += ySpeed;
repaint();

try {

Thread.sleep(16); // Sleep for a short time to control animation speed

} catch (InterruptedException e) {

e.printStackTrace();

private void changeColor() {

colorIndex = (colorIndex + 1) % colors.length;

setBackground(colors[colorIndex]);

public void paint(Graphics g) {

g.setColor(Color.WHITE);

g.fillRect(0, 0, getWidth(), getHeight());

g.setColor(colors[colorIndex]);

g.fillOval(x, y, 20, 20);

Slip 30 A) Write a java program to accept a number from a user, if it is zero then throw user defined Exception “Number
is Zero”. If it is non-numeric then generate an error “Number is Invalid” otherwise check whether it is palindrome or not.

Answer :

import java.io.*;

class Numberiszero extends Exception{}

class Slip30A{

public static void main( String args[]){

int r,sum=0,temp;

int n;
DataInputStream dr = new DataInputStream(System.in);

try {

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

n = Integer.parseInt(dr.readLine());

if(n==0){

throw new Numberiszero();

}else{

temp=n;

while(n>0){

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum){

System.out.println("Palindrome Number ");

}else{

System.out.println("Not Palindrome");

} catch (Numberiszero nz) {

System.out.println("Number is Zero");

catch (NumberFormatException e){

System.out.println("Number is Invalid");

catch (Exception e){}

You might also like