0% found this document useful (0 votes)
5 views89 pages

Java Programs for Beginners: Examples

The document contains multiple Java programming tasks and their solutions, including displaying alphabets, copying non-numeric data from files, handling mouse events, checking for Armstrong numbers, and calculating areas and volumes of geometric shapes. It also includes tasks for string manipulation, matrix transposition, exception handling, and validating user input for mobile and PAN numbers. Each task is accompanied by code snippets demonstrating the implementation in Java.

Uploaded by

bodkekimaya
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)
5 views89 pages

Java Programs for Beginners: Examples

The document contains multiple Java programming tasks and their solutions, including displaying alphabets, copying non-numeric data from files, handling mouse events, checking for Armstrong numbers, and calculating areas and volumes of geometric shapes. It also includes tasks for string manipulation, matrix transposition, exception handling, and validating user input for mobile and PAN numbers. Each task is accompanied by code snippets demonstrating the implementation in Java.

Uploaded by

bodkekimaya
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

Slip 1 - A) Write a ‘java’ program to display characters from ‘A’ to ‘Z’.

Solution :

public class DisplayAlphabet {

public static void main(String[] args) {

for(char ch = 'A'; ch <= 'Z'; ch++) {

[Link](ch + " ");

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

Solution :

import [Link].*;

public class CopyNonNumeric {

public static void main(String[] args) {

String sourceFile = "[Link]";

String destFile = "[Link]";

try {

FileReader fr = new FileReader(sourceFile);

FileWriter fw = new FileWriter(destFile);

int ch;

while ((ch = [Link]()) != -1) {

if (![Link]((char) ch)) {

[Link](ch);

[Link]();

[Link]();

[Link]("Non-numeric data copied successfully!");

} catch (IOException e) {

[Link]("Error: " + [Link]()); } }


}Slip 2 - A) Write a java program to display all the vowels from a given string.

Solution:

public class DisplayVowels {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");

String str = [Link]();

[Link]("Vowels in the string are: ");

for (int i = 0; i < [Link](); i++) {

char ch = [Link]([Link](i)); // Convert to lowercase

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

[Link]([Link](i) + " "); // Print original character

[Link]();

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

Solution:

import [Link].*;

import [Link].*;

public class MouseEventDemo extends Frame implements MouseListener, MouseMotionListener {

TextField tf; public MouseEventDemo() {

setLayout(new FlowLayout());

tf = new TextField(30);

add(tf);
addMouseListener(this);

addMouseMotionListener(this);

setTitle("Mouse Event Demo");

setSize(400, 400);

setVisible(true);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

});

public void mouseClicked(MouseEvent me) {

int x = [Link]();

int y = [Link]();

[Link]("Mouse Clicked at: X=" + x + " Y=" + y);

public void mousePressed(MouseEvent me) {}

public void mouseReleased(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

public void mouseExited(MouseEvent me) {}

public void mouseMoved(MouseEvent me) {

setTitle("Mouse Moved at: X=" + [Link]() + " Y=" + [Link]());

public void mouseDragged(MouseEvent me) {}

public static void main(String[] args) {

new MouseEventDemo();

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

Solution:

import [Link];
public class Slip_3_1_A {
static int temp;
public static void main(String agrs[]){
Scanner scan=new Scanner([Link]);

[Link]("Enter a number: ");


int num=[Link]();
int sum=0,rem;
temp=num;
while(num>0){
rem=num%10;
sum=sum+(rem*rem*rem);
num=num/10;
}
if(sum==temp){
[Link]("Number is Armstrong");
}
else{
[Link]("Number is not Armstrong");
}
[Link]();
}
}

Output:

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

Solution:
import [Link];

abstract class Shape{


int a,b;
Shape(int x, int y){
a = x;
b = y;
}
abstract double area();
abstract double volume();
}
class Cone extends Shape{
Cone(int x, int y){
super(x,y);
}
double area(){
return (a*b*3.14);
}
double volume(){
return (3.14*a*a*b);
}
}
class Cylinder extends Shape{
Cylinder(int x, int y){
super(x,y);
}
double area(){
return (2*3.14*a*b*3.14*a*b);
}
double volume(){
return (3.14*a*a*b);
}
}

class Slip3B{
public static void main(String args[]) throws Exception{
int r,h,s;
Scanner scan = new Scanner([Link]);
[Link]("Enter Radius, Height and Side Values : ");
r = [Link]();
h = [Link]();
s = [Link]();
Shape s1;
Cone c1 = new Cone(r,s);
s1=c1;
[Link]("Area of Cone is : " + [Link]());
[Link]("Volume of Cone is : " +[Link]());
Cylinder cy = new Cylinder(r,h);
s1 =cy;
[Link]("Area of Cylinder is : " + [Link]());
[Link]("Area of Cylinder is : " + [Link]());
}
}

Output:

Sip 4 - A) Write a java program to display alternate character from a given string.[

Solution:

import [Link];
class Slip4A {
public static void main(String args[]){
Scanner scan=new Scanner([Link]);

try {
[Link]("Enter String : ");
String str = [Link]();
for(int i=0;i<[Link]();i+=2) {
[Link](" " + [Link](i));
}
} catch (Exception e) {}
}
}

Output:
Slip 4 - B) Write a java program using Applet to implement a simple arithmetic calculator.

Solution:

import [Link].*;

import [Link].*;

import [Link].*;

/*

<applet code="SimpleCalculatorApplet" width=400 height=200>

</applet>

*/

public class SimpleCalculatorApplet extends Applet implements ActionListener {

TextField tf1, tf2, tfResult;

Button addBtn, subBtn, mulBtn, divBtn;

public void init() {

setLayout(new FlowLayout());

tf1 = new TextField(10);

tf2 = new TextField(10);

tfResult = new TextField(15);

[Link](false); // Result field is read-only

add(new Label("Number 1:"));

add(tf1);

add(new Label("Number 2:"));

add(tf2);

addBtn = new Button("Add");

subBtn = new Button("Subtract");

mulBtn = new Button("Multiply");

divBtn = new Button("Divide");

add(addBtn);

add(subBtn);

add(mulBtn);
add(divBtn);

add(new Label("Result:"));

add(tfResult);

[Link](this);

[Link](this);

[Link](this);

[Link](this);

public void actionPerformed(ActionEvent e) {

try {

double num1 = [Link]([Link]());

double num2 = [Link]([Link]());

double result = 0;

if ([Link]() == addBtn) {

result = num1 + num2;

} else if ([Link]() == subBtn) {

result = num1 - num2;

} else if ([Link]() == mulBtn) {

result = num1 * num2;

} else if ([Link]() == divBtn) {

if (num2 != 0) {

result = num1 / num2;

} else {

[Link]("Cannot divide by zero");

return;

[Link]([Link](result));

} catch (NumberFormatException ex) {

[Link]("Invalid Input");

} }}
Slip 5 - A) Write a java program to display following pattern: 5 4 5 3 4 5 2 3 4 5 1 2 3 4 5

Solution:

public class Slip5

public static void main( String[] args) {

int n=6;

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

for (int j = n-i; j<n; j++) {

[Link](j+" ");

[Link]();

Output:

Slip 5 - B) Write a java program to accept list of file names through command line. Delete the files
having extension .txt. Display name, location and size of remaining files.

Solution:
import [Link].*;
class Slip5B{
public static void main(String args[]) throws Exception{
for(int i=0;i<[Link];i++){
File file=new File(args[i]);
if([Link]()){
String name = [Link]();
if([Link](".txt")){
[Link]();
[Link]("file is deleted " + file);
}else{
[Link]("File Name : " + name + "\nFile Location : " +[Link]()+"\
nFile Size : "+[Link]()+" bytes");
}
}
else{
[Link](args[i]+ "is not a file");
}
}
}
}

Output:

Slip 6 - A) Write a java program to accept a number from user, if it zero then throw user defined
Exception “Number Is Zero”, otherwise calculate the sum of first and last digit of that number. (Use
static keyword).

Solution:

import [Link];

class NumZero extends Exception{}

public class Slip6A {

static int n;

public static void main(String args[]){

int first,last=0;

Scanner scan = new Scanner([Link]);


try {

[Link]("Enter Number : ");

n = [Link]();

if(n!=0){

last = n % 10;

first = n;

while(n>=10){

n = n / 10;

first=n;

[Link]("Sum of First and Last Number is : " + (first + last));

}else{

throw new NumZero();

} catch (NumZero nz) {

[Link]("Number is Zero");

catch(Exception e){}

Output:
slip 6 - B) Write a java program to display transpose of a given matrix.

Solution:

public class MatrixTransposeExample{

public static void main(String args[]){

//creating a matrix

int original[][]={{1,3,4},{2,4,3},{3,4,5}};

//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];

[Link]("Printing Matrix without transpose:");

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

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

[Link](original[i][j]+" ");

[Link]();//new line

[Link]("Printing Matrix After Transpose:");

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

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

[Link](transpose[i][j]+" ");

[Link]();//new line
}

}}

Output:

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

Solution:

import [Link].*;

public class Slip7A extends Frame{

public void paint(Graphics g){

Font f = new Font("Georgia",[Link],20);

[Link](f);

[Link]("Dr D Y Patil College", 50, 70);

setBackground([Link]);

public static void main(String args[]){

Slip7A sl = new Slip7A();

[Link](true);

[Link](500,300);

}
Output:

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

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

Solution:

import [Link].*;

interface Shape{
final float pi= 3.14F;
double area();
}
class Circle implements Shape{
int rad;
Circle(int r){
rad=r;
}
public double area(){
return pi*rad*rad;
}
}
class Sphere implements Shape{
int rad;
Sphere(int r){
rad =r;
}
public double area(){
return 4*pi*rad*rad;
}
}

class Slip8A {
public static void main(String args[]) throws Exception{
int r;
Scanner sc = new Scanner([Link]);
[Link]("Enter the Radius : ");
r=[Link]();

Shape sh;
Circle cl=new Circle(r);
sh=cl;
[Link]("Area of Circle : " + [Link]());

Sphere sp=new Sphere(r);


sh=sp;
[Link]("Area of Sphare : "+[Link]());
}

Output:

Slip 8 - B) Write a java program to display the files having extension .txt from a given directory.

Solution:

import [Link];
class Slip8B {
public static void main(String[] args) {
File file = new File(" Your File Path ");
String[] fileList = [Link]();
for(String str : fileList) {
if([Link](".txt")){
[Link](str);
}
}
}
}

Output:

Slip 9 - A) Write a java Program to display following pattern: 1 0 1 0 1 0 1 0 1 0

Solution:

class Slip9A {
public static void main(String args[]){
int i,j,k=1;;
for(i=1; i<=4; i++){
for(j=1; j<=i; j++){
if(k%2==1){
[Link](1 + " ");
}else{
[Link](0 + " ");
}
k++;
}
[Link]();
}
}

Output:
Slip 9 - B) 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.

Solution:

import [Link];

class invaliddetails extends Exception{}

class Slip9B{

static int n;

public static void main( String args[]){

Scanner scan= new Scanner([Link]);

try {

[Link]("********* Do you Want to Validate ********* \n1. Mobile Number


Press : 1 \n2. PAN Card Press : 2 \nEnter Number : ");

n = [Link]();

switch(n){

case 1 :

[Link]("Enter Mobile Number : ");

Long num = [Link]();

if([Link]().matches("(0/91)?[7-9][0-9]{9}")){

[Link]("Valid Mobile Number..!");

}else{

throw new invaliddetails();

break;

case 2 :
[Link]("Enter PAN Number : ");

String str= [Link]();

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

[Link]("Valid PAN CARD Number..!");

}else{

throw new invaliddetails();

break;

default :

throw new invaliddetails();

} catch (invaliddetails nz) {

[Link]("You Enter Invalid Details...!");

catch (NumberFormatException e){

[Link]("You Enter Invalid Details...!");

catch(Exception e){}

Output:

Slip 10 - A) Write a java program to count the frequency of each character in a given string.

Solution:

public class Slip10A

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

String str = "Coding Activity";

int[] freq = new int[[Link]()];

int i, j;

//Converts given string into character array

char string[] = [Link]();

for(i = 0; i <[Link](); i++) {

freq[i] = 1;

for(j = i+1; j <[Link](); j++) {

if(string[i] == string[j]) {

freq[i]++;

//Set string[j] to 0 to avoid printing visited character

string[j] = '0';

//Displays the each character and their corresponding frequency

[Link]("Characters and their corresponding frequencies");

for(i = 0; i <[Link]; i++) {

if(string[i] != ' ' && string[i] != '0')

[Link](string[i] + "-" + freq[i]);

Output:
Slip 10 - B) Write a java program for the following:

Solution:

import [Link].*;

import [Link].*;

import [Link].*;

class Slip10B extends JFrame implements ActionListener{

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

JTextField t1,t2,t3,t4,t5;

JButton b1,b2,b3;

Panel p1,p2,p3,p4,p5;

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

JFrame jf;

public Slip10B(){

jf = new JFrame();

l1 = new JLabel("Simple Interest Calculator");

[Link](JLabel. CENTER);

l2 = new JLabel("Principle Amount");

l3 = new JLabel("Interest Rate(%)");

l4 = new JLabel("Time(Yrs)");

l5 = new JLabel("Total Amount");


l6 = new JLabel("Interest Amount");

t1 = new JTextField(20);

t2 = new JTextField(20);

t3 = new JTextField(20);

t4 = new JTextField(20);

t5 = new JTextField(20);

b1 = new JButton("Calculate");

b2 = new JButton("Clear");

b3 = new JButton("Close");

p1 = new Panel();

g1= new GridLayout(1,1);

[Link](g1);

[Link](l1);

p2 = new Panel();

g2 = new GridLayout(1,2);

[Link](g2);

[Link](l2);

[Link](t1);

p3 = new Panel();

g3 = new GridLayout(1,4);

[Link](g3);

[Link](l3);

[Link](t2);

[Link](l4);

[Link](t3);
p4 = new Panel();

g4 = new GridLayout(2,2);

[Link](g4);

[Link](l5);

[Link](t4);

[Link](l6);

[Link](t5);

p5 = new Panel();

g5 = new GridLayout(1,3);

[Link](g5);

[Link](b1);

[Link](b2);

[Link](b3);

g6 = new GridLayout(5,1);

[Link](g6);

[Link](p1);

[Link](p2);

[Link](p3);

[Link](p4);

[Link](p5);

[Link](500,250);

[Link](true);

[Link](this);

[Link](this);

[Link](this);

}
public void actionPerformed(ActionEvent ae){

int p = [Link]([Link]());

float rt = [Link]([Link]());

float tm = [Link]([Link]());

if([Link]()==b1){

float r=rt/100;

double iamt = p * [Link](1 + (r / 12), 12 * tm);

double tamt = iamt-p;

[Link]([Link](iamt));

[Link]([Link](tamt));

if([Link]()==b2){

[Link]("");

[Link]("");

[Link]("");

[Link]("");

[Link]("");

if([Link]()==b3){

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String args[]){

Slip10B s1 = new Slip10B();

}
Output:

Slip 11 - A) Write a menu driven java program using command line arguments for the following: 1.
Addition 2. Subtraction 3. Multiplication 4. Division.

Solution :

import [Link];

public class Slip11A {

public static void main(String args[]){

int a,b,n;

[Link]("Enter 1 : Additon" + '\n' + "Enter 2 : Substraction" + '\n' + "Enter 3 :


Multiplication" + '\n' + "Enter 4 : Division");

Scanner dr=new Scanner([Link]);

try {

a = [Link](args[0]);

b = [Link](args[1]);

[Link]("Enter Number : ");

n = [Link]();

switch(n){

case 1:

[Link](a + " + " + b + " = " + (a+b));

break;

case 2:

[Link](a + " - " + b + " = " + (a-b));

break;

case 3:

[Link](a + " * " + b + " = " + (a*b));


break;

case 4:

[Link](a + " / " + b + " = " + (a/b));

break;

} catch (Exception e) {}

Output:

Slip 11 - B) Write an applet application to display Table lamp. The color of lamp should get change
randomly.

Solution :

import [Link].*;

import [Link].*;

public class Slip11B extends Applet{

public float R,G,B;

Graphics gl;

public void init(){

repaint();

public void paint(Graphics g){

R = (float)[Link]();

G = (float)[Link]();

B = (float)[Link]();
Color cl = new Color(R,G,B);

[Link](0,250,290,290);

[Link](125,250,125,160);

[Link](175,250,175,160);

[Link](85,157,130,50,-65,312);

[Link](85,87,130,50,62,58);

[Link](85,177,119,89);

[Link](215,177,181,89);

[Link](cl);

[Link](78,120,40,40,63,-174);

[Link](120,96,40,40);

[Link](173,100,40,40,110,180);

/*

<applet code="[Link]" width="300" height="300">

</applet>

*/

Output:
Slip 12 - A) Write a java program to display each String in reverse order from a String array.

Solution :

class Slip12A{

public static void main(String args[]){

String arr[] = {"for you", "activity", "Coding"};

for(int i=[Link]-1; i>=0; i--){

[Link](arr[i] + ' ');

}
}

Output:

Slip 12 - B) Write a java program to display multiplication table of a given number into the List box
by clicking on button.

Solution :

import [Link].*;

import [Link].*;

import [Link].*;

public class Slip12B extends Applet implements ActionListener{

Button b1 = new Button("Show");

List Multi = new List();

String str ="";

public void init(){

[Link]("1");

[Link]("2");

[Link]("3");

[Link]("4");

[Link]("5");

[Link]("6");

[Link]("7");

[Link]("8");

[Link]("9");

[Link]("10");
add(Multi);

add(b1);

[Link](this);

public void paint(Graphics g){

int count = 100;

int num = [Link]([Link]());

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

int a = num*i;

[Link](i +" * " + i +" = "+ a,100,count);

count = count+20;

public void actionPerformed(ActionEvent e){

repaint();

/*

<applet code="[Link]" width="300" height="300">

</applet>

*/

Output:
Slip 13 - A) 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.

Solution :

import [Link].*;

import [Link];

class Slip13A{

public static void main(String args[]){

String temp=null;

int i,j,n;

Scanner dr=new Scanner([Link]);

try{
[Link]("Enter How May Element You Want = ");

n = [Link]();

[Link]();

String name[]= new String[n];

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

[Link]("Enter " + (i+1) + " String = ");

name[i] = [Link]();

[Link]("After Sorting = ");

for(i=n-1; i>=0; i--){

[Link](name[i] + " ");

}catch(Exception e){}

Output:
Slip 13 - B) Write a java program that asks the user name, and then greets the user by name.
Before outputting the user's name, convert it to upper case letters. For example, if the user's name
is Raj, then the program should respond "Hello, RAJ, nice to meet you!".

Solution :

import [Link];

class Slip13B {

public static void main(String args[]){

String str;

Scanner dr=new Scanner([Link]);

try {

[Link]("Enter Username : ");

str = [Link]();

[Link]("\"Hello, " + [Link]() + ", nice to meet you!\"");

} catch (Exception e) {}

}
Output:

Slip 14 - A) Write a Java program to calculate power of a number using recursion.

Solution :

import [Link].*;

class Slip14A {

public static void main(String args[]){

int base,exp;

Scanner sc =new Scanner([Link]);

[Link]("Enter the Base Number : ");

base = [Link]();

[Link]("Enter the Exponent Number : ");

exp = [Link]();

int result = power(base, exp);

[Link]("Answer : "+ result);

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


if(exp!=0){

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

}else{

return 1;

Output:

Slip 14 - B) Write a java program to accept the details of employee (Eno, EName, Sal) and display it
on next frame using appropriate event .

Solution :

import [Link].*;

import [Link].*;

class Emp_details implements ActionListener {

Frame f;

Label empno, empname, sal;

TextField tempno, tempname, tsal;

Button next;
Emp_details() {

f = new Frame("\t Employee Details:");

empno = new Label("\t Employee Id:");

empname = new Label("\t Employee Name:");

sal = new Label("\t Employee Sal:");

tempno = new TextField(25);

tempname = new TextField(25);

tsal = new TextField(25);

next = new Button("Next");

[Link](empno);

[Link](tempno);

[Link](empname);

[Link](tempname);

[Link](sal);

[Link](tsal);

[Link](next);

[Link](this);

[Link](new FlowLayout());

[Link](400, 400);

[Link](true);

public void actionPerformed(ActionEvent ae) {

String empno, empname, sal;

empno = [Link]();

empname = [Link]();

sal = [Link]();

[Link](false);

new FrameDetails(empno, empname, sal);

}
class FrameDetails extends Frame {

Frame f;

Label empno, empname, sal;

TextField tempno, tempname, tsal;

FrameDetails(String no, String name, String s) {

f = new Frame("Employee Details:");

empno = new Label("Employee ID:");

empname = new Label("Employee Name:");

sal = new Label("Employee Salary:");

tempno = new TextField(25);

tempname = new TextField(25);

tsal = new TextField(25);

[Link](empno);

[Link](tempno);

[Link](empname);

[Link](tempname);

[Link](sal);

[Link](tsal);

[Link](no);

[Link](name);

[Link](s);

[Link](new FlowLayout());

[Link](400, 400);

[Link](true);

class Slip14B {

public static void main(String args[]) {


new Emp_details();

Output:

Slip 15 - A) Write a java program to search given name into the array, if it is found then display its
index otherwise display appropriate message.

Solution :

import [Link];

class Slip15A{

public static void main(String args[]){

String arr[] = {"saurabh", "Sapkal", "Mahesh","priya"};

int i,n=0;
boolean a=false;

DataInputStream dr = new DataInputStream([Link]);

try {

[Link]("Enter String : ");

String s= [Link]();

for(i = 0; i < [Link]; i++)

if(arr[i].equals(s))

n = i;

a = true;

break;

if(a){

[Link]("arr" + "["+ i + "]");


}else{

[Link]("not Found");

} catch (Exception e) {}

Output:

Slip 15 - B) Write an applet application to display smiley face.

Solution :

import [Link];

import [Link];

public class Slip15B extends Applet{

public void paint(Graphics g){

[Link](80, 70, 150, 150);


[Link](120, 120, 15, 15);

[Link](170, 120, 15, 15);

[Link](130, 180, 50, 20, 180, 180);

/*

<applet code="[Link]" width="300" height="300">

</applet>

*/

Output:
Slip 16 - A) Write a java program to calculate sum of digits of a given number using recursion.

Solution :

import [Link].*;

public class Slip16A {

int sum =0;

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

int n;

Scanner s = new Scanner([Link]);

[Link]("Enter the Number : ");


n =[Link]();

Slip16A obj = new Slip16A();

int a = obj.sum_digit(n);

[Link]("Sum of Digit is : "+a);

int sum_digit(int n){

sum = n%10;

if(n==0){

return 0;

}else{

return sum +sum_digit(n/10);

Output:
Slip 16 - B) 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)

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

Solution :

class Slip17A{

public static void main(String args[]){

int num,i,r,sum=0,temp,count=0;;

num = [Link];

int a[]= new int[num];

int b[]= new int[10];

for(i=0; i<num; i++){

a[i] = [Link](args[i]);

sum =0;

temp =a[i];

while(a[i]!=0){

r = a[i]%10;

sum = sum+r*r*r;

a[i] = a[i]/10;

if(temp==sum){

b[count] = temp;

count++;
}

for(i=0; i<count; i++){

[Link](b[i] + " ");

Output:

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

Solution :

import [Link].*;

class Product{

String pname;

int pid, qty;

float price, total;

void accept(){

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));


try {

[Link]("Enter the producat Name : ");

pname=[Link]();

[Link]("Enter pid, qty and price : ");

pid = [Link]([Link]());

qty = [Link]([Link]());

price = [Link]([Link]());

} catch (Exception e) { }

void display(){

total = qty*price;

[Link]("pid : " + pid + "\nProduct Nmae : "+pname+"\nQuantity : "+qty + "\nPrice :


"+price+"\n Total Amount : "+total);

}
class Slip17B {

public static void main(String args[]) throws IOException{

int n;

float to=0;

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

[Link]("How many Product you want to enter : ");

n = [Link]([Link]());

Product p1[]=new Product[n];

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

p1[i]=new Product();

p1[i].accept();

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

p1[i].display();

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


to=to+p1[i].total;

[Link]("Total Cost : "+to);

Output:

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

Solution :

import [Link].*;

class AreaCalculate{
void area(int r){

[Link]("Area of Cirlce = " + (3.14*r*r));

float area(int b, float h){

return b*h/2;

double area(Float l, Float db){

return l+db;

class Slip18A {

public static void main(String args[]){

int r, b, l, db;

float h;

Scanner br = new Scanner([Link]);

[Link]("Enter the radius, base, height, length and breadth : ");

r = [Link]();

b = [Link]();

h = [Link]();

l = [Link]();

db = [Link]();

AreaCalculate ac = new AreaCalculate();

[Link](r);

[Link]("Area of Triangle = " +[Link](b,h));


[Link]("Area of Rectange = " +[Link](l,db));

Output:

Slip 18 - B) Write a java program to copy the data from one file into another file, while copying
change the case of characters in target file and replaces all digits by ‘*’ symbol.

Solution :

import [Link].*;

class Slip18B{

public static void main(String args[]) throws IOException{

FileReader fr = new FileReader("[Link]");

FileWriter fw = new FileWriter("[Link]");

int c;

while ((c=[Link]())!=-1){

if([Link](c)==false){
if([Link](c)){

[Link]([Link](c));

}else if([Link](c)){

[Link]([Link](c));

}else{

[Link]('*');

[Link]();

[Link]();

Output:

[Link]
[Link]

Slip 19 - A) Write a Java program to display Fibonacci series using function.

Solution :

import [Link];

class Slip19A {

static void fibo() {

int i,a,b,c,n;

Scanner scan=new Scanner([Link]);

try {

[Link]("Enter Number : ");

n = [Link]();

a = b = 1;

[Link]("The Fibonacci sequence: " + a + " " + b);

for(i=1; i<=n-2; i++){

c = a + b;

[Link](" "+c);

a = b;

b = c;

} catch (Exception e) {}

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

fibo();

Output:

Slip 19 - B) Create an Applet that displays the x and y position of the cursor movement using
Mouse and Keyboard. (Use appropriate listener).

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.

Solution :

import [Link].*;

import [Link].*;

class Slip20A {

public static void main(String args[]) {

JFrame frame = new JFrame("TYBBACA");

[Link](400, 400);

[Link](JFrame.EXIT_ON_CLOSE);

[Link]().setBackground([Link]);

[Link](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 ListIterator.
Solution :

import [Link].*;

public class Slip20B{

public static void main (String args[]){

LinkedList al = new LinkedList<>();

[Link]("CPP");

[Link]("JAVA");

[Link]("Python");

[Link]("PHP");

[Link]("Display content using Iterator...");

Iterator il=[Link]();

while([Link]()){

[Link]([Link]());

[Link]("Display Content Revverse Using ListIterator");

ListIterator li1=[Link]();
while([Link]()){

[Link]();

while([Link]()){

[Link]("" + [Link]());

Output:

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

Solution :

import [Link].*;

import [Link];
class Slip21A{

public static void main(String args[]) throws IOException{

FileReader fr = new FileReader("[Link]");

FileWriter fw = new FileWriter("[Link]");

try (Scanner dr = new Scanner(fr)) {

while([Link]()){

String s=[Link]();

StringBuffer buffer = new StringBuffer(s);

buffer=[Link]();

String ans = [Link]();

[Link](ans);

}catch(Exception e){

[Link]("Error...!");

[Link]();

[Link]();

Output:

[Link]

[Link]
Slip 21 - B) 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.

Solution :

import [Link].*;

import [Link];

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;

Scanner dr=new Scanner([Link]);

try {

[Link]("Enter the Now Many Record You Want : ");

n = [Link]();

[Link]();

[Link]("Enter the City Name & STD Code : ");

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

cname = [Link]();

std = [Link]();

[Link]();

[Link](cname,std);

}
[Link]("Enter city name to search : ");

nm = [Link]();

en=[Link]();

while([Link]()){

str=(String)[Link]();

val=(Integer)[Link](str);

if([Link](nm)){

[Link]("STD Code : " + val);

} catch (Exception e) {}

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

Solution :

import [Link];

public class Slip22A {

public static void main(String[] args) {

Scanner scan=new Scanner([Link]);

[Link]("Enter any number: ");

int num = [Link]();

long factorial = multiplyNumbers(num);

[Link]("Factorial of " + num + " : " + factorial);

public static long multiplyNumbers(int num)

{
if (num >= 1)

return num * multiplyNumbers(num - 1);

else

return 1;

Output:

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.

Solution :

import [Link].*;

import [Link].*;

class Slip22B {

public static void main(String args[]) throws IOException{

Scanner br = new Scanner([Link]);

[Link]("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");

[Link]("Enter File Name : ");

String str = [Link]();

File file = new File(str);

[Link]("Enter Number : ");

int num = [Link]();

switch(num){
case 1 :

if ([Link]()) {

[Link]("File created : " + [Link]());

} else {

[Link]("File already exists.");

case 2 :

[Link]("Enter New File Name : ");

String newone = [Link]();

File newfile =new File(newone);

if([Link](newfile)){

[Link]("File renamed");

}else{

[Link]("Sorry! the file can't be renamed");

break;

case 3 :

if ([Link]()) {

[Link]("Deleted the file: " + [Link]());

} else {

[Link]("Failed to delete the file.");

break;

case 4 :

[Link]("File Location : " +[Link]());

break;

default : [Link]("Wrong Number ..!");

break;

}
Output:

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.

Solution :

import [Link].*;

import [Link].*;

public class Slip23A {

public static void main(String[] args) {

Scanner br = new Scanner([Link]);

try {

[Link]("Enter File Name : ");

String str = [Link]();

File file = new File(str);


if([Link]()){

[Link]("File is Hidden");

}else{

[Link]("File Location : " +[Link]());

} catch(Exception e) {

[Link]();

Output:

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

Solution :

import [Link].*;

import [Link].*;
public class Slip23B extends JFrame implements ActionListener{

public static void main(String s[]){

new Slip23B();

public Slip23B(){

[Link](600,500);

[Link](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/[Link]");

ImageIcon SaveIcon = new ImageIcon("icons/[Link]");

ImageIcon QuitIcon = new ImageIcon("icons/[Link]");

ImageIcon UndoIcon = new ImageIcon("icons/[Link]");

ImageIcon RedoIcon= new ImageIcon("icons/[Link]");

ImageIcon CutIcon = new ImageIcon("icons/[Link]");


ImageIcon CopyIcon = new ImageIcon("icons/[Link]");

ImageIcon PasteIcon = new ImageIcon("icons/[Link]");

[Link](OpenItem);

[Link](SaveItem);

[Link](QuitItem);

[Link](UndoItem);

[Link](RedoItem);

[Link](CutItem);

[Link](CopyItem);

[Link](PasteItem);

[Link](OpenIcon);

[Link](SaveIcon);
[Link](QuitIcon);

[Link](UndoIcon);

[Link](RedoIcon);

[Link](CutIcon);

[Link](CopyIcon);

[Link](PasteIcon);

[Link](filMenu);

[Link](filEdit);

[Link](filSearch);

[Link](menuBar);

[Link](true);

}
@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

Output:

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

Solution :

import [Link].*;

class Slip24A{

public static void main(String args[]) throws IOException{


FileReader fr = new FileReader("[Link]");

int c;

int letter=0;

int space=0;

int num=0;

int other=0;

while ((c=[Link]())!=-1){

if([Link](c)){

num ++;

}else if([Link](c)){

letter++;

}else if([Link](c)){

space++;

}else{
other ++;

[Link]("Numbers : " + num + "\nLetters : "+letter+"\nSpace : "+space+"\nSpecial


Characters : "+other);

[Link]();

[Link]();

Output:

[Link]
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)

Solution :

import TYBBACA.*;

import [Link].*;

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([Link]);

[Link]("How Many Student's record You Want :");

n1 = [Link]([Link]());

[Link]("How Many Teacher's record You Want :");

n2 = [Link]([Link]());

Student s1[] = new Student[n1];

Teacher t1[] = new Teacher[n2];

[Link]("Enter Student Details");

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

[Link]("Enter roll no, Student name and Percentage");

r = [Link]([Link]());

snm=[Link]();

per=[Link]([Link]());

s1[i] = new Student(r,snm,per);

[Link]("Enter Teacher Details");

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

[Link]("Enter Teacher id , Teacher name and Subject");


t = [Link]([Link]());

tnm=[Link]();

sub=[Link]();

t1[j] = new Teacher(t,tnm,sub);

[Link]("Student Details");

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

((Student) s1[i]).disp();

[Link]("Teacher Details");

String str ="java";

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

if([Link](t1[j].sub)){

t1[j].disp();

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

Solution :

import [Link];

public class Slip25A {

public static void main(String args[]){

int i=0,h=0;

Scanner scan=new Scanner([Link]);

try {
[Link]("Enter String : ");

String str = [Link]();

int j= [Link]()-1;

while(i<j){

if([Link](i++) != [Link](j--)){

h=h+i;

if(h>0){

[Link]("String is not palindrome");

}else{

[Link]("String is palindrome");

} catch (Exception e) {}

}
Output:

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.

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

Solution :

import [Link].*;
class Slip26A{
public static void main(String args[]) throws IOException{
char ch;
FileReader fr = new FileReader("[Link]");
int c;
while ((c=[Link]())!=-1){
ch=(char)c;
if([Link](ch)==false && ([Link](c)==false)){
[Link]("ASCII "+ch+" : "+ c);
}
}
[Link]();
}
}

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

Solution :

import [Link];

import [Link];

import [Link];

public class Slip26B extends Applet{

public void init() {

setBackground([Link]);
}

public void paint(Graphics g){

[Link]([Link]);

[Link](100, 150, 90, 120);

[Link](130, 230, 20, 40);

[Link](150, 100, 100, 150);

[Link](150, 100, 190, 150);

[Link](150, 50, 150, 100);

[Link]([Link]);

[Link](150, 50, 20, 20);

/*

<applet code="[Link]" width="300" height="300">


</applet>

*/

Output:

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).

Solution :

import [Link].*;

class NumOutRange extends Exception{}

class Slip27A{

static int n;

public static void main( String args[]){

DataInputStream dr = new DataInputStream([Link]);

try {
[Link]("Enter Number : ");

n = [Link]([Link]());

if(n>1000){

throw new NumOutRange();

}else{

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

if(n%i==0){

[Link](i + " ");

} catch (NumOutRange nz) {

[Link]("Num is out of range..!");

catch (Exception e){

[Link](""+[Link]());

Output:
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.

Solution :

import [Link].*;

import [Link].*;

import [Link].*;

public class Slip27B extends Frame implements ActionListener{

Graphics g;

List l;

TextField t1;

Button b1;

Label l1;

public Slip27B(){

[Link](new FlowLayout());

[Link](400,400);

[Link](true);

l1 = new Label("Enter Directory ");


t1 = new TextField(20);

l = new List(10);

b1 = new Button("Display");

[Link](50,100,80,80);

[Link](50,150,80,80);

[Link](50,200,80,80);

[Link](50,300,100,100);

add(l1);

add(t1);

add(b1);

add(l);

[Link](this);

public void actionPerformed(ActionEvent e){

if([Link]()==b1){

try{

String nm = [Link]();

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

String s1[]=[Link]();

if(s1==null){

[Link]("Dir not exist");

}else{

for(int i=0; i<[Link]; i++){

[Link](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).

Solution :

import [Link].*;

public class Slip28A {

public static void main(String[] args) {

int count = 0;

List<String> al = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {

[Link](args[i]);

for (int i = 0; i < [Link](); i++) {

String element = [Link](i);

try {

int j = [Link](element);

count++;

} catch (NumberFormatException e) {}

[Link](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.

Solution:

import [Link].*;

public class Question_2 {

JFrame f;

JTable j;

Question_2(){

f = new JFrame();

[Link]("Employee Details");

String data[][] = {

{"1","Tushar","50,000"},

{"2","Mihir","20,000"},

{"3","ANurag","25,000"},

{"4","Abhishekr","20,000"},

};

String[] columnNames = {"Eno", "Ename", "Salary" };

j = new JTable(data, columnNames);

[Link](30,40,200,300);

JScrollPane sp = new JScrollPane(j);

[Link](sp);

[Link](500,200);

[Link](true);

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

new Question_2();

Output:

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.

Solution:

import [Link].*;

class Voting

public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link]("Enter your Name: ");


String name=[Link]();

[Link]("Enter your age: ");

int age=[Link]();

if((age>=18)&&(age<=100))

[Link]("Congratulation "+name+", You are eligible for Voting");

else

[Link]("Sorry "+name+", You are not eligible for voting");

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

Solution:

import [Link].*;

import [Link].*;

import [Link].*;

//

/* Program By Ghanendra Yadav

Visit [Link]

*/

public class BOUNCINGBALLS extends Applet implements MouseListener, Runnable

Thread t=null;

int x1=10, x2=10, x3=10, x4=10;

int y1=300, y2=300, y3=300, y4=300;


int flagx1,flagy1,flagx2,flagy2;

int flagx3,flagy3,flagx4,flagy4;

public void init()

addMouseListener(this);

public void mouseExited(MouseEvent me) {}

public void mouseReleased(MouseEvent me) {}

public void mouseEntered(MouseEvent me) {}

public void mousePressed(MouseEvent me) {}

public void mouseClicked(MouseEvent me) {}

public void start()

t=new Thread(this);

[Link]();

public void run()

for(;;)

try

repaint();

if(y1<=50)

flagx1=0;

else if(y1>=300)

flagx1=1;

if(x1<=10)
flagy1=0;

else if(x1>=400)

flagy1=1;

if(y2<=50)

flagx2=0;

else if(y2>=300)

flagx2=1;

if(x2<=10)

flagy2=0;

else if(x2>=400)

flagy2=1;

if(y3<=50)

flagx3=0;

else if(y3>=300)

flagx3=1;

if(x3<=10)

flagy3=0;

else if(x3>=400)

flagy3=1;

if(y4<=50)

flagx4=0;

else if(y4>=300)

flagx4=1;

if(x4<=10)

flagy4=0;

else if(x4>=400)

flagy4=1;

[Link](10);

}catch(InterruptedException e){}

}
public void paint(Graphics g)

[Link](10,50,410,270);

[Link]([Link]);

[Link](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;

[Link]([Link]);

[Link](x2,y2,20,20);

if(flagx2==1)

y2-=4;

else if(flagx2==0)

y2+=4;

if(flagy2==0)

x2+=3;

else if(flagy2==1)

x2-=3;

[Link]([Link]);

[Link](x3,y3,20,20);

if(flagx3==1)

y3-=6;

else if(flagx3==0)

y3+=6;

if(flagy3==0)
x3+=2;

else if(flagy3==1)

x3-=2;

[Link]([Link]);

[Link](x4,y4,20,20);

if(flagx4==1)

y4-=5;

else if(flagx4==0)

y4+=5;

if(flagy4==0)

x4+=1;

else if(flagy4==1)

x4-=1;

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.

Solution:

import [Link].*;

import [Link];

class abc extends Exception{}

class slip{

public static void main( String args[]){


int r,sum=0,temp;

int n;

Scanner dr=new Scanner([Link]);

try {

[Link]("Enter Number : ");

n = [Link]();

if(n==0){

throw new abc();

}else{

temp=n;

while(n>0){

r=n%10;
sum=(sum*10)+r;

n=n/10;

if(temp==sum){

[Link]("It is Palindrome Number ");

}else{

[Link]("Not Palindrome");

} catch (abc nz) {

[Link]("Number is 0");
}

catch (NumberFormatException e){

[Link]("Invalid Number ");

catch (Exception e){}

Output:

Slip 30 - B) Write a java program to design a following GUI (Use Swing).

You might also like