java
java
import java.io.*;
class Main {
char 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 {
int c;
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 {
char 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 {
int 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 {
str.charAt(i) == 'U')
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.*;
TextField statusBar;
Slip4()
addMouseListener(new MouseAdapter()
repaint();
repaint();
});
addWindowListener(new WindowAdapter()
System.exit(0);
});
setLayout(new FlowLayout());
setSize(275,300);
setVisible(true);
new Slip4();
Write a java program to display all the vowels from a given string.
import java.io.*;
class Vowel {
str.charAt(i) == 'U')
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.*;
TextField statusBar;
Slip4()
addMouseListener(new MouseAdapter()
repaint();
repaint();
});
addWindowListener(new WindowAdapter()
System.exit(0);
});
setLayout(new FlowLayout());
setSize(275,300);
setVisible(true);
new Slip4();
Write a ‘java’ program to check whether given number is Armstrong or not.(Use static keyword)
import java.util.Scanner;
num = scan.nextInt();
temp = num;
while(temp!=0)
rem = temp%10;
temp = temp/10;
if(num==res)
System.out.println("\nArmstrong Number.");
else
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.*;
int r,s,h;
super();
this.r=r;
this.s=s;
this.h=h;
int r,h;
Cylinder(int r,int h)
this.r=r;
this.h=h;
class Slip15
int r =sc.nextInt();
int s1 =sc.nextInt();
int h =sc.nextInt();
Shape s;
s=new Cone(r,s1,h);
s.area();
s.vol();
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;
num = scan.nextInt();
temp = num;
while(temp!=0)
rem = temp%10;
if(num==res)
System.out.println("\nArmstrong Number.");
else
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.*;
int r,s,h;
super();
this.r=r;
this.s=s;
this.h=h;
}
public void vol()
int r,h;
Cylinder(int r,int h)
this.r=r;
this.h=h;
class Slip15
int r =sc.nextInt();
int s1 =sc.nextInt();
int h =sc.nextInt();
Shape s;
s=new Cone(r,s1,h);
s.area();
s.vol();
r =sc.nextInt();
h =sc.nextInt();
s=new Cylinder(r,h);
s.area();
s.vol();
Slip4
import java.util.Scanner;
System.out.println("Enter an string");
try{
System.out.println(str1.charAt(i));
} catch(StringIndexOutOfBoundsException e) {
System.out.println("String index out of bounds. String length: " + str1.length());
Calculator.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
TextField t1;
char choice;
setBackground(k);
t1 = new TextField(10);
setLayout(g1);
t1.addActionListener(this);
add(t1);
add(b[i]);
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(equals);
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);
}
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)
break;
break;
break;
break;
break;
t1.setText("" + result);
}
Calculator.html
import java.util.Scanner;
System.out.println("Enter an string");
try{
System.out.println(str1.charAt(i));
} catch(StringIndexOutOfBoundsException e) {
}
}
Calculator.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
TextField t1;
char choice;
setBackground(k);
t1 = new TextField(10);
setLayout(g1);
t1.addActionListener(this);
add(t1);
add(b[i]);
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(equals);
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);
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)
break;
break;
break;
break;
break;
t1.setText("" + result);
}
}
Calculator.html
45
345
2345
12345
import java.io.*;
{
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);
}
}
}
import java.io.*;
public class Matrix{
//creating a matrix
int original[][]={{10,30,40},{20,40,30},{30,40,50}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
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
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
10 30 40
20 40 30
30 40 50
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.*;
Slip7()
setForeground(Color.blue);
setBackground(Color.red);
add(l);
setLayout(new FlowLayout());
setSize(200,200);
setVisible(true);
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;
int n = scanner.nextInt();
double maxAverage = 0;
int maxAverageIndex = 0;
maxAverage = players[i].average;
maxAverageIndex = i;
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;
// Specify the directory path where you want to search for .txt files
if (files != null) {
System.out.println(file.getName());
} else {
} else {
Output
a.txt
b.txt
Write a java Program to display following Pattern:
01
010
1010
int numToPrint = (i % 2 == 0) ? 1 : 0;
numToPrint = 1 - numToPrint;
System.out.println();
Output:-
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.
super(message);
}
try {
validatePAN(panNumber);
validateMobileNumber(mobileNumber);
} catch (InvalidDataException e) {
if (pan.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {
// PAN is valid
} else {
if (mobileNumber.matches("[0-9]{10}")) {
} else {
throw new InvalidDataException("Invalid Mobile Number");
OutPut
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.*;
if (charFrequencyMap.containsKey(c)) {
} else {
charFrequencyMap.put(c, 1);
}
}
Output
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 InterestCalculatorAWT() {
setTitle("Interest Calculator");
setSize(400, 200);
setLayout(null);
add(l1);
p = new TextField();
add(p);
add(r1);
r = new TextField();
add(r);
add(l3);
add(time1);
calculate = new Button("Calculate");
add(calculate);
add(clear);
add(close);
total.setEditable(false);
add(total);
interestAmount.setEditable(false);
add(interestAmount);
calculate.addActionListener(new ActionListener() {
calculate();
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clear();
});
close.addActionListener(new ActionListener() {
System.exit(0);
});
addWindowListener(new WindowAdapter() {
dispose();
});
setVisible(true);
try {
} catch (NumberFormatException e) {
total.setText("Invalid input");
interestAmount.setText("Invalid input");
p.setText("");
r.setText("");
time1.setText("");
total.setText("");
interestAmount.setText("");
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.*;
if (args.length != 3) {
System.out.println("CommandLine Argument");
return;
double result = 0;
switch (operation) {
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
if (num2 == 0) {
} else {
}
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>
Write an applet application to display Table lamp.The color of lamp should get change randomly
import java.applet.*;
import java.awt.*;
resize(300,300);
}
// the platform
g.fillRect(0,250,290,290);
g.drawLine(125,250,125,160);
g.drawLine(175,250,175,160);
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);
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>
</body>
</html>
Output-
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public MultiplicationTableApp() {
setTitle("Multiplication Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 400);
displayButton.addActionListener(new ActionListener() {
@Override
tableModel.clear();
try {
});
panel.add(numberField);
panel.add(displayButton);
panel.add(new JScrollPane(tableList));
add(panel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
app.setVisible(true);
});
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;
int n = scanner.nextInt();
numberList.add(num);
System.out.println(numberList.get(i));
scanner.close();
Enter 3 integers:
123
124
125
125
124
123
import java.util.Scanner;
import java.io.*;
if (exp !=0){
}else {
return 1;
}
}
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.*;
int number = 123; // Change this to the number you want to calculate the sum for
if (num == 0) {
} else {
// Calculate the sum of digits for the remaining part of the number
}
}
Write a java program to accept n employee names from user. Sort them in ascending
import java.io.*;
import java.util.Scanner;
String name;
Employee(String name)
this.name = name;
{
if (employees[i].name.compareTo(employees[j].name) > 0)
employees[i] = employees[j];
employees[j] = temp;
int n = scanner.nextInt();
Employee.sortEmployeesByName(employees);
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.*;
if (args.length == 0) {
return;
int n = args.length;
try {
numbers[i] = Integer.parseInt(args[i]);
} catch (NumberFormatException e) {
if (isArmstrongNumber(number)) {
armstrongNumbers.add(number);
if (armstrongNumbers.isEmpty()) {
} else {
System.out.println(armstrongNumber);
originalNumber = number;
while (originalNumber != 0) {
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;
this.pid = pid;
this.pname = pname;
this.price = price;
this.qty = qty;
}
public void displayProduct() {
System.out.print("Price: $");
System.out.print("Quantity: ");
}
System.out.println("Product Details:");
double totalAmount = 0;
product.displayProduct();
totalAmount += productTotal;
System.out.println();
Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method Overloading)
import java.util.Scanner;
import java.io.*;
switch (choice) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
System.out.println("Invalid choice");
}
public static double calculateArea(double radius) {
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
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;
addMouseListener(new MyMouseListener());
addKeyListener(new MyKeyListener());
setFocusable(true);
requestFocus();
g.drawString("Mouse Position: (" + mouseX + ", " + mouseY + ")", 10, 20);
mouseX = e.getX();
mouseY = e.getY();
repaint();
if (e.getKeyCode() == KeyEvent.VK_UP) {
mouseY--;
mouseY++;
mouseX--;
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;
frame.setBackground(Color.RED);
// Add a window listener to close the frame when the close button is clicked
frame.addWindowListener(new WindowAdapter() {
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:
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Iterator;
names.add("CPP");
names.add("Java");
names.add("Python");
names.add("PHP");
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Display the contents of the list in reverse order using a ListIterator
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.*;
citySTDTable.put("Chicago", "312");
citySTDTable.put("Boston", "617");
if (stdCode != null) {
} else {
}
}
import java.util.Scanner;
int n = scanner.nextInt();
if (n < 0) {
} else {
if (n == 0 || n == 1) {
return 1;
} else {
To create a file.
To rename a file.
To delete a file.
import java.io.File;
import java.io.IOException;
// Create a file
createFile("sample.txt");
// Rename a file
renameFile("sample.txt", "newSample.txt");
displayFilePath("newSample.txt");
// Delete a file
deleteFile("newSample.txt");
}
public static void createFile(String fileName) {
try {
if (file.createNewFile()) {
} else {
} catch (IOException e) {
e.printStackTrace();
if (oldFile.renameTo(newFile)) {
} else {
if (file.delete()) {
} else {
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;
String filePath = "path_to_your_file_here"; // Replace with the file path you want to check
if (file.isHidden()) {
} else {
} else {
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
exitMenuItem.addActionListener(new ActionListener() {
System.exit(0);
});
fileMenu.add(exitMenuItem);
editMenu.add(undoMenuItem);
editMenu.add(redoMenuItem);
editMenu.addSeparator(); // Separator
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
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;
int digitCount = 0;
int spaceCount = 0;
int characterCount = 0;
int c;
char ch = (char) c;
if (Character.isDigit(ch)) {
digitCount++;
} else if (Character.isWhitespace(ch)) {
spaceCount++;
characterCount++;
} catch (IOException e) {
e.printStackTrace();
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 Student() { }
public Student(int R, String S1,double P)
{ Rno=R;
SName=S1;
Per=P;
System.out.println(Rno);
System.out.println(SName);
System.out.println(Per);
System.out.println("Student Details...");
}}
Teacher.java
package bca;
public Teacher(){ }
TID = T;
TName = TN;
Subject = Sub;
}
System.out.println(TID);
System.out.println(TName);
System.out.println(Subject);
{System.out.println("Teacher Details..."); }
Test.java
import bca.*;
System.out.println("Student Details...");
for(int i=0;i<students.length;i++)
students[i].display();
System.out.println("Teacher Details...");
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>
import java.util.Scanner;
if (isPalindrome(input)) {
} else {
int left = 0;
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
Fibonacci.java
package Series;
int a = 0, b = 1;
int sum = a + b;
a = b;
b = sum;
CubeOfNumbers.java
package Series;
int cube = i * i * i;
SquareOfNumbers.java
package Series;
int square = i * i;
}
}
SeriesMain.java
import Series.*;
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;
int character;
} catch (IOException e) {
e.printStackTrace();
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
super(message);
try {
int number = 1200; // Replace with the number you want to check
} else {
displayFactors(number);
} catch (NumberOutOfRangeException e) {
System.err.println(e.getMessage());
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 DirectoryLister() {
setTitle("Directory Lister");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
listButton.addActionListener(new ActionListener() {
@Override
listDirectoryContents();
});
panel.add(directoryField);
panel.add(listButton);
add(panel, "North");
add(scrollPane, "Center");
fileList.setListData(contents);
} else {
directoryLister.setVisible(true);
});
Write a java program to count the number of integers from a given list. (Use Command line arguments).
if (args.length == 0) {
return;
int count = 0;
try {
count++;
} catch (NumberFormatException e) {
// Ignore non-integer arguments
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;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
tableModel.addColumn("Employee Number");
tableModel.addColumn("Employee Name");
tableModel.addColumn("Salary");
frame.add(scrollPane);
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;
super(message);
}
}
try {
throw new AgeBelow18Exception("Candidate is not eligible for voting as age is below 18.");
} else {
} catch (AgeBelow18Exception e) {
System.err.println(e.getMessage());
} catch (InputMismatchException e) {
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 {
x = 100;
y = 100;
xSpeed = 3;
ySpeed = 2;
t.start();
while (true) {
xSpeed = -xSpeed; // Reverse direction when hitting the left or right edge
changeColor();
ySpeed = -ySpeed; // Reverse direction when hitting the top or bottom edge
changeColor();
x += xSpeed;
y += ySpeed;
repaint();
try {
} catch (InterruptedException e) {
e.printStackTrace();
setBackground(colors[colorIndex]);
g.setColor(Color.WHITE);
g.setColor(colors[colorIndex]);
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 Slip30A{
int r,sum=0,temp;
int n;
DataInputStream dr = new DataInputStream(System.in);
try {
n = Integer.parseInt(dr.readLine());
if(n==0){
}else{
temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
if(temp==sum){
}else{
System.out.println("Not Palindrome");
System.out.println("Number is Zero");
System.out.println("Number is Invalid");