[go: up one dir, main page]

0% found this document useful (0 votes)
51 views24 pages

Core - JavaSlip 20 - 30

The document contains practical Java programming exercises for a T.Y. BBA(CA) course, covering topics such as GUI creation with AWT, linked lists, file handling, recursion, and exception handling. Each slip includes a specific task, such as creating frames, manipulating data structures, and performing file operations, along with sample code solutions. The exercises aim to enhance students' understanding of core Java concepts through hands-on programming experience.

Uploaded by

shivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views24 pages

Core - JavaSlip 20 - 30

The document contains practical Java programming exercises for a T.Y. BBA(CA) course, covering topics such as GUI creation with AWT, linked lists, file handling, recursion, and exception handling. Each slip includes a specific task, such as creating frames, manipulating data structures, and performing file operations, along with sample code solutions. The exercises aim to enhance students' understanding of core Java concepts through hands-on programming experience.

Uploaded by

shivani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

T.Y.

BBA(CA) Sem – V

Subject : Core java (Practical Slip Solution)

Slip No: 20 to 30

Slip 20 A) 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.

Answer :

import javax.swing.*;

import java.awt.*;

class Slip20A {

public static void main(String args[]) {

JFrame frame = new JFrame("TYBBACA");

frame.setSize(400, 400);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setBackground(Color.RED);

frame.setVisible(true);

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

i. Display the contents of the List using an Iterator

ii. Display the contents of the List in reverse order using a List Iterator.

Answer :
import java.util.*;
public class Slip20B{
public static void main (String args[]){
LinkedList al = new LinkedList<>();
al.add("CPP");
al.add("JAVA");
al.add("Python");
al.add("PHP");
System.out.println("Display content using Iterator...");
Iterator il=al.iterator();
while(il.hasNext()){
System.out.println(il.next());
}
System.out.println("Display Content Revverse Using ListIterator");
ListIterator li1=al.listIterator();
while(li1.hasNext()){
li1.next();
}
while(li1.hasPrevious()){
System.out.println("" + li1.previous());
}
}
}

Slip 21 A) Write a java program to display each word from a file in reverse order.

Answer :
import java.io.*;
import java.util.Scanner;
class Slip21A{
public static void main(String args[]) throws IOException{
FileReader fr = new FileReader("a.txt");
FileWriter fw = new FileWriter("b.txt");
try (Scanner dr = new Scanner(fr)) {
while(dr.hasNextLine()){
String s=dr.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String ans = buffer.toString();
fw.write(ans);
}
}catch(Exception e){
System.out.print("Error...!");
}
fr.close();
fw.close();
}
}

Slip 21 B) Create a hash table containing city name & STD code. Display the details of
the hash table. Also search for a specific city and display STD code of that city.

Answer :
import java.util.*;
import java.io.*;
public class Slip21B {
public static void main(String args[]){
Hashtable h1=new Hashtable<>();
Enumeration en;
int i,n,std,val,max=0;
String nm, cname, str, s=null;
DataInputStream dr = new DataInputStream(System.in);
try {
System.out.print("Enter the Now Many Record You Want : ");
n = Integer.parseInt(dr.readLine());
System.out.print("Enter the City Name & STD Code : ");
for(i=0; i<n; i++){
cname = dr.readLine();
std = Integer.parseInt(dr.readLine());
h1.put(cname,std);
}
System.out.print("Enter city name to search : ");
nm = dr.readLine();
en=h1.keys();
while(en.hasMoreElements()){
str=(String)en.nextElement();
val=(Integer)h1.get(str);
if(str.equals(nm)){
System.out.print("STD Code : " + val);
}
}
} catch (Exception e) {}
}
}

Slip 22 A) Write a Java program to calculate factorial of a number using recursion.

Answer :
public class Slip22A {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " : " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}

Slip 22 B) Write a java program for the following:


1. To create a file.
2. To rename a file.
3. To delete a file.
4. To display path of a file.

Answer :
import java.io.*;
import java.util.*;
class Slip22B {
public static void main(String args[]) throws IOException{
Scanner br = new Scanner(System.in);

System.out.println("1. Press 1 Create File\n2. Press 2 Rename a File\n3.


Press 3 Delete a File\n4. Press 4 Display Path of a File");

System.out.print("Enter File Name : ");


String str = br.nextLine();
File file = new File(str);
System.out.print("Enter Number : ");
int num = br.nextInt();

switch(num){

case 1 :
if (file.createNewFile()) {
System.out.println("File created : " + file.getName());
} else {
System.out.println("File already exists.");
}

case 2 :
System.out.print("Enter New File Name : ");
String newone = br.nextLine();
File newfile =new File(newone);
if(file.renameTo(newfile)){
System.out.println("File renamed");a
}else{
System.out.println("Sorry! the file can't be renamed");
}
break;

case 3 :
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
break;

case 4 :
System.out.println("File Location : " +file.getAbsolutePath());
break;
default :
System.out.println("Wrong Number ..!");
break;
}
}
}

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

Answer :
import java.io.*;
import java.util.*;
public class Slip23A {
public static void main(String[] args) {
Scanner br = new Scanner(System.in);
try {
System.out.print("Enter File Name : ");
String str = br.nextLine();
File file = new File(str);
if(file.isHidden()){
System.out.println("File is Hidden");
}else{
System.out.println("File Location : " +file.getAbsolutePath());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Slip 23 B) Write a java program to design following Frame using Swing.

Answer :
import java.awt.event.*;
import javax.swing.*;

public class Slip23B extends JFrame implements ActionListener{


public static void main(String s[]){
new Slip23B();
}

public Slip23B(){
this.setSize(600,500);
this.setLocation(200,200);

JMenuBar menuBar = new JMenuBar();


JMenu filMenu = new JMenu("File");
JMenu filEdit = new JMenu("Edit");
JMenu filSearch = new JMenu("Search");
JMenuItem OpenItem = new JMenuItem("Open");
JMenuItem SaveItem = new JMenuItem("Save");
JMenuItem QuitItem = new JMenuItem("Quit");

JMenuItem UndoItem = new JMenuItem("Undo");


JMenuItem RedoItem = new JMenuItem("Redo");
JMenuItem CutItem = new JMenuItem("Cut");
JMenuItem CopyItem = new JMenuItem("Copy");
JMenuItem PasteItem = new JMenuItem("Paste");

ImageIcon OpenIcon = new ImageIcon("icons/open.png");


ImageIcon SaveIcon = new ImageIcon("icons/Save.png");
ImageIcon QuitIcon = new ImageIcon("icons/Delete.png");

ImageIcon UndoIcon = new ImageIcon("icons/Undo.png");


ImageIcon RedoIcon= new ImageIcon("icons/Redo.png");
ImageIcon CutIcon = new ImageIcon("icons/Cut.png");
ImageIcon CopyIcon = new ImageIcon("icons/Copy.png");
ImageIcon PasteIcon = new ImageIcon("icons/Past.png");

filMenu.add(OpenItem);
filMenu.add(SaveItem);
filMenu.add(QuitItem);

filEdit.add(UndoItem);
filEdit.add(RedoItem);
filEdit.add(CutItem);
filEdit.add(CopyItem);
filEdit.add(PasteItem);

OpenItem.setIcon(OpenIcon);
SaveItem.setIcon(SaveIcon);
QuitItem.setIcon(QuitIcon);

UndoItem.setIcon(UndoIcon);
RedoItem.setIcon(RedoIcon);
CutItem.setIcon(CutIcon);
CopyItem.setIcon(CopyIcon);
PasteItem.setIcon(PasteIcon);

menuBar.add(filMenu);
menuBar.add(filEdit);
menuBar.add(filSearch);

this.setJMenuBar(menuBar);
this.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

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

Answer :
import java.io.*;
class Slip24A{
public static void main(String args[]) throws IOException{
FileReader fr = new FileReader("a.txt");
FileWriter fw = new FileWriter("b.txt");
int c;
int letter=0;
int space=0;
int num=0;
int other=0;

while ((c=fr.read())!=-1){
if(Character.isDigit(c)){
num ++;
}else if(Character.isLetter(c)){
letter++;
}else if(Character.isSpaceChar(c)){
space++;
}else{
other ++;
}
}
fw.write("Numbers : " + num + "\nLetters : "+letter+"\nSpace :
"+space+"\nSpecial Characters : "+other);
fr.close();
fw.close();
}
}

Slip 24 B) 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)

Answer :
import TYBBACA.*;
import java.io.*;

public class Slip24B {


public static void main(String args[])throws Exception{
int r,n1,n2,t;
String snm, tnm, sub;
float per;
DataInputStream dr = new DataInputStream(System.in);
System.out.println("How Many Student's record You Want :");
n1 = Integer.parseInt(dr.readLine());
System.out.println("How Many Teacher's record You Want :");
n2 = Integer.parseInt(dr.readLine());
Student s1[] = new Student[n1];
Teacher t1[] = new Teacher[n2];
System.out.println("Enter Student Details");
for (int i=0; i<n1; i++){
System.out.println("Enter roll no, Student name and Percentage");
r = Integer.parseInt(dr.readLine());
snm=dr.readLine();
per=Float.parseFloat(dr.readLine());
s1[i] = new Student(r,snm,per);
}
System.out.println("Enter Teacher Details");
for (int j=0; j<n2; j++){
System.out.println("Enter Teacher id , Teacher name and Subject");
t = Integer.parseInt(dr.readLine());
tnm=dr.readLine();
sub=dr.readLine();
t1[j] = new Teacher(t,tnm,sub);
}
System.out.println("Student Details");
for (int i=0; i<n1; i++){
((Student) s1[i]).disp();
}
System.out.println("Teacher Details");
String str ="java";
for (int j=0; j<n2; j++){
if(str.equals(t1[j].sub)){
t1[j].disp();
}
}
}
}

Slip 25 A) Write a java program to check whether given string is palindrome or not.

Answer :
import java.io.DataInputStream;
public class Slip25A {
public static void main(String args[]){
int i=0,h=0;
DataInputStream dr = new DataInputStream(System.in);
try {
System.out.print("Enter String : ");
String str = dr.readLine();
int j= str.length()-1;
while(i<j){
if(str.charAt(i++) != str.charAt(j--)){
h=h+i;
}
}
if(h>0){
System.out.println("String is not palindrome");
}else{
System.out.println("String is palindrome");
}
} catch (Exception e) {}
}
}

Slip 25 B) Create a package named Series having three different classes to print series:

i. Fibonacci series

ii. Cube of numbers

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

Answer :
import java.io.*;
import Series.*;

class Slip25B {
public static void main(String args[])throws Exception{
int n1,n2,n3;
DataInputStream dr = new DataInputStream(System.in);
System.out.print("Enter How Many fibonnacci series you want : ");
n1=Integer.parseInt(dr.readLine());
System.out.print("Enter How Many cube you want : ");
n2=Integer.parseInt(dr.readLine());
System.out.print("Enter How Many Squares you want : ");
n3=Integer.parseInt(dr.readLine());

System.out.println("\nFibonacci Series ....");


Fibo f1 = new Fibo();
f1.fiboSeries(n1);

System.out.println("\nCube Series ....");


Cubes c1=new Cubes();
c1.cubeSeries(n2);

System.out.println("\nSquare Series ....");


Square s1=new Square();
s1.squareSeries(n3);
}
}

//Create folder series

//Cubes.java

package Series;

public class Cubes {


public void cubeSeries(int n){
for(int i=1; i<=n; i++){
int c=(i*i*i);
System.out.print(c + " ");
}
}
}

//Fibo.java

package Series;

public class Fibo {


public int f=0, s=1, i;
public void fiboSeries(int nl){
for(i=1; i<=nl; i++){
System.out.print(f + " ");
int n=f+s;
f=s;
s=n;
}
}
}

//Square.java

package Series;

public class Square {


public void squareSeries(int n){
for(int i=1; i<=n; i++){
int c=(i*i);
System.out.print(c +" ");
}
}
}

Slip 26 A) Write a java program to display ASCII values of the characters from a file.

Answer :
import java.io.*;
class Slip26A{
public static void main(String args[]) throws IOException{
char ch;
FileReader fr = new FileReader("a.txt");
int c;
while ((c=fr.read())!=-1){
ch=(char)c;
if(Character.isDigit(ch)==false &&
(Character.isSpaceChar(c)==false)){
System.out.println("ASCII "+ch+" : "+ c);
}
}
fr.close();
}
}

Slip 26 B) Write a java program using applet to draw Temple.

Answer :
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Slip26B extends Applet{

public void init() {


setBackground(Color.BLACK);
}
public void paint(Graphics g){
g.setColor(Color.WHITE);
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.setColor(Color.ORANGE);
g.drawRect(150, 50, 20, 20);
}

}
/*
<applet code="Slip26B.class" width="300" height="300">
</applet>
*/

Slip 27 A) 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)

Answer :
import java.io.*;
class NumOutRange extends Exception{}
class Slip27A{
static int n;
public static void main( String args[]){
DataInputStream dr = new DataInputStream(System.in);
try {
System.out.print("Enter Number : ");
n = Integer.parseInt(dr.readLine());
if(n>1000){
throw new NumOutRange();
}else{
for(int i=1; i<n; i++){
if(n%i==0){
System.out.println(i + " ");
}
}
}
} catch (NumOutRange nz) {
System.out.println("Num is out of range..!");
}
catch (Exception e){
System.out.println(""+e.getMessage());
}
}
}

Slip 27 B) 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.

Answer :

import java.awt.*;

import java.awt.event.*;

import java.io.*;

public class Slip27B extends Frame implements ActionListener{

Graphics g;
List l;

TextField t1;

Button b1;

Label l1;

public Slip27B(){

this.setLayout(new FlowLayout());

this.setSize(400,400);

this.setVisible(true);

l1 = new Label("Enter Directory ");

t1 = new TextField(20);

l = new List(10);

b1 = new Button("Display");

l1.setBounds(50,100,80,80);

t1.setBounds(50,150,80,80);

b1.setBounds(50,200,80,80);

l.setBounds(50,300,100,100);

add(l1);

add(t1);

add(b1);

add(l);

b1.addActionListener(this);

public void actionPerformed(ActionEvent e){

if(e.getSource()==b1){
try{

String nm = t1.getText();

File f1 = new File(nm + ":");

String s1[]=f1.list();

if(s1==null){

System.out.println("Dir not exist");

}else{

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

l.add(s1[i]);

}catch(Exception ee){}

public static void main(String args[]){

new Slip27B();

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

Answer :

import java.util.*;

public class Slip28A {

public static void main(String[] args) {

int count = 0;
List<String> al = new ArrayList<>();

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

al.add(args[i]);

for (int i = 0; i < al.size(); i++) {

String element = al.get(i);

try {

int j = Integer.parseInt(element);

count++;

} catch (NumberFormatException e) {}

System.out.println(count + " integers present in list");

Output :

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

Answer :
import javax.swing.*;
public class Slip28B {
JFrame f;
JTable j;
Slip28B(){
f = new JFrame();
f.setTitle("Employee Details");
String data[][] = {
{"1","Radhika Sapkal","50,000"},
{"2","Ramesh Devakar","20,000"},
{"3","Hardik Shrinivas","25,000"},
{"4","Bhihari Kumar","20,000"},
{"5","Swaraghini Pawar","15,000"},
};
String[] columnNames = {"Eno", "Ename", "Salary" };
j = new JTable(data, columnNames);
j.setBounds(30,40,200,300);
JScrollPane sp = new JScrollPane(j);
f.add(sp);
f.setSize(500,200);
f.setVisible(true);
}

public static void main(String args[]) {


new Slip28B();
}
}

Slip 29 A) Write a java program to check whether given candidate is eligible for voting
or not. Handle user defined as well as system defined Exception.

Answer :
import java.io.*;
class NumOutRange extends Exception{}
class Slip29A{
static int n;
public static void main( String args[]){
DataInputStream dr = new DataInputStream(System.in);
try {
System.out.print("Enter Age : ");
n = Integer.parseInt(dr.readLine());
if(n<18){
throw new NumOutRange();
}else{
System.out.print("You Are eligible For Voting :) ");
}
} catch (NumOutRange nz) {
System.out.println("You Are Not eligible For Voting ....!");
}
catch (Exception e){}
}
}

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

Answer :

import java.applet.*;

import java.awt.*;

public class Slip29B extends Applet implements Runnable {

Thread t = null;
int x1 = 10;

int y1 = 300;

int flagx1, flagy1;

int R, G, B;

public void start() {

t = new Thread(this);

t.start();

public void color(){

R = (int) (Math.random() * 256);

G = (int) (Math.random() * 256);

B = (int) (Math.random() * 256);

public void run() {

for (;;) {

try {

repaint();

if (y1 <= 50) {

flagx1 = 0;

color();

} else if (y1 >= 300) {

flagx1 = 1;

color();

}
if (x1 <= 10) {

flagy1 = 0;

color();

} else if (x1 >= 400) {

flagy1 = 1;

color();

Thread.sleep(10);

} catch (InterruptedException e) {

public void paint(Graphics g) {

Color color = new Color(R, G, B);

g.setColor(color);

g.fillOval(x1, y1, 20, 20);

if (flagx1 == 1)

y1 -= 2;

else if (flagx1 == 0)

y1 += 2;

if (flagy1 == 0)

x1 += 4;

else if (flagy1 == 1)

x1 -= 4;

}
}

/*

* <applet code="Slip29B.class" width="420" height="320">

* </applet>

*/

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){}
}
}
Slip 30 B) Write a java program to design a following GUI (Use Swing).

Answer :

import javax.swing.*;

import java.awt.*;

class Slip30B extends JFrame{

JLabel l1,l2,l3,l4,l5,l6;

JTextField t1,t2,t3,t4;

JButton b1,b2;

JRadioButton rb1, rb2;

JCheckBox ch1,ch2,ch3;

Panel p1,p2,p3,p4,p5,p6;

GridLayout g1,g2,g3,g4,g5,g6,g7;

JFrame jf;

public Slip30B(){

jf = new JFrame();

l1 = new JLabel("",JLabel.CENTER);

l1.setText("<HTML><U>Personal Information</U></HTML>");

p1 = new Panel();

g1 = new GridLayout(1,1);
p1.setLayout(g1);

p1.add(l1);

l1.setFont( new Font("Times New Roman",Font.BOLD,20));

l2 = new JLabel(" First Name : ");

t1 = new JTextField(30);

l3 = new JLabel(" Last Name : ");

t2 = new JTextField(30);

p2 = new Panel();

g2 = new GridLayout(2,1);

p2.setLayout(g2);

p2.add(l2);

p2.add(t1);

p2.add(l3);

p2.add(t2);

l4 = new JLabel(" Address : ");

t3 = new JTextField(30);

l5 = new JLabel(" Mobile Number : ");

t4 = new JTextField(30);

p3 = new Panel();

g3 = new GridLayout(2,1);

p3.setLayout(g3);

p3.add(l4);

p3.add(t3);
p3.add(l5);

p3.add(t4);

l5 = new JLabel(" Gender ");

rb1 = new JRadioButton("Male");

rb2 = new JRadioButton("Female");

ButtonGroup bg = new ButtonGroup();

bg.add(rb1);

bg.add(rb2);

p4 = new Panel();

g4 = new GridLayout(1,2);

p4.setLayout(g4);

p4.add(l5);

p4.add(rb1);

p4.add(rb2);

l6 = new JLabel(" Your Interests");

ch1 = new JCheckBox("Comuter");

ch2 = new JCheckBox("Sport");

ch3 = new JCheckBox("Music");

p5 = new Panel();

g5 = new GridLayout(1,2);

p5.setLayout(g5);

p5.add(l6);
p5.add(ch1);

p5.add(ch2);

p5.add(ch3);

b1 = new JButton("Submit");

b2 = new JButton("Reset");

p6 = new Panel();

g6 = new GridLayout(1,1,400,10);

p6.add(b1);

p6.add(b2);

this.setSize(500,250);

this.setVisible(true);

g7 = new GridLayout(6,1);

this.setLayout(g7);

this.add(p1);

this.add(p2);

this.add(p3);

this.add(p4);

this.add(p5);

this.add(p6);
}

public static void main(String args[]){

new Slip30B();

You might also like