0% found this document useful (0 votes)
60 views43 pages

Java Practicals

The document contains 11 Java programs that demonstrate various programming concepts: 1. A program that displays a greeting through command line arguments. 2. A program that calculates the factorial of a user-input number and checks if it is negative. 3. A program that converts days to months and years. 4. A program that prints numbers between 1-100 divisible by 5 but not 10. 5. A program that calculates the sum of even numbers up to a user-input value. 6. A program that defines a Friend class with properties and displays an object. 7. A program that demonstrates different constructors of a class.

Uploaded by

Yash Amin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
60 views43 pages

Java Practicals

The document contains 11 Java programs that demonstrate various programming concepts: 1. A program that displays a greeting through command line arguments. 2. A program that calculates the factorial of a user-input number and checks if it is negative. 3. A program that converts days to months and years. 4. A program that prints numbers between 1-100 divisible by 5 but not 10. 5. A program that calculates the sum of even numbers up to a user-input value. 6. A program that defines a Friend class with properties and displays an object. 7. A program that demonstrates different constructors of a class.

Uploaded by

Yash Amin
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 43

1.

Write a program to display input provided through command


line arguments.

// 1.Program

import java.lang.*;
import java.util.*;

public class Hello


{
public static void main(String args[])
{
System.out.println("Hello, I'm Aditya....");
}
}

2.factorial of a enter number. Check the entered number, if it‟s


negative then an error message should print.

// 2.Program

import java.util.*;

public class Factorial


{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int i,num,fact=1;
System.out.print("Enter The Number: ");
num = sc.nextInt();
if (0 >= num)
{
System.out.println("Its Negative value. Enter Positive
value.");
}
else
{
for (i=1;i<=num;i++)
{
fact = fact * i;
}
System.out.println("Factorial Of " + num + " is " + fact);
}
}
}

3.Write a program to convert given no. of days into months, years


and days; assume that each month is of 30 days. For Example: if
input is 69 than Output is 2 months and 9 days.

// 3.Program
import java.util.*;

public class Days


{
public static void main(String[] args)
{
int m,year,month,day;
Scanner s = new Scanner(System.in);
System.out.print("Enter The no of Days: ");
m = s.nextInt();
year = m / 365;
month = m / 30;
day = m % 30;
System.out.println("No. of Years: " + year);
System.out.println("No. of Month: " + month);
System.out.println("No. of Days: " + day);
}
}

4. Write a program that prints the numbers between 1 and 100


which are divisible by 5 but not divisible by 10.

// 4.Program
import java.util.*;
public class Numbers
{
public static void main(String[] args)
{
int i=1;
System.out.println("Divided by 5 but not 10 : ");
for (i=1;i<100;i++)
{
if (i%5==0 && i%10 !=0)
{
System.out.println(i);
}
}
}
}

5.Write a program to calculate sum of even number till n numbers.


[ N number is provided through command line arguments]

// 5.Program
import java.util.*;

public class SumOfEvenNumbers


{
public static void main(String[] args)
{
int num,i,sum=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter any Number: ");
num = s.nextInt();

for (i=1;i<=num;i++ )
{
if (i%2==0)
{
sum = sum + i;
}
}
System.out.println("The Sum Of Even Number Upto " + num + " =
" + sum);
}
}

6.Create class “Friend” which have following properties:


Data Members: name, address, mobile-no and email-id.
Method: display.
Write a program which will insert details of Friend through no
argument constructor and display information of it through
display method.

//6.Program

import java.util.*;
class Friend1
{
String name,address,email;
long mobileno;
Scanner sc=new Scanner(System.in);

Friend1() //default constructor.


{
System.out.println("Enter your Friend name:");
name=sc.next();
System.out.println("Enter Your Friend Address: ");
address=sc.next();
System.out.println("Enter Your Friend E-mail: ");
email=sc.next();
System.out.println("Enter Your Friend Mobile No: ");
mobileno=sc.nextLong();
}

void display()
{
System.out.println("Your Friend Name is "+name+". Address is
"+address+". E-mail is "+email+".");
System.out.println("Mobile No is "+mobileno);
}

public static void main(String args[])


{
Friend1 f=new Friend1();

f.display();
}
}

7.Use above class structure and perform following task:


Create default constructor, one argument constructor, two
argument constructor and copy constructor.
Call all the above created constructor one by one and display
information of it through function.

//7.Program
import java.util.*;
import java.io.*;
import java.lang.*;

public class Constructor


{
int no;
String name;

public static void main(String[] args)


{
Constructor c1 = new Constructor();
Constructor c2 = new Constructor("YASH");
Constructor c3 = new Constructor("RAHUL",38);
Constructor c4 = new Constructor(c2);
c1.display();
c2.display();
c3.display();
c4.display();
}

Constructor()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your Name: ");
name = sc.next();
System.out.println("Enter Your No. ");
no = sc.nextInt();
}

Constructor(String s)
{
name = s;
}

Constructor(String s,int i)
{
name = s;
no = i;
}

Constructor(Constructor c)
{
name = c.name;
}

void display()
{
System.out.println("Name is " + name + " and no is " + no);
}
}

8.Create class “Student” which have following properties:


Data Members: enrolmentNo, name,course, and fee.
Methods: insert and display.
Write a program which will insert and display student
information through class methods.
// 8.Program
import java.util.*;

class Student
{
public static void main(String args[])
{
int eno_no,fee;
String name,course;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Enrollment No: ");
eno_no = sc.nextInt();
System.out.print("Enter Name: ");
name = sc.next();
System.out.print("Enter course: ");
course = sc.next();
System.out.print("Enter Fee: ");
fee = sc.nextInt();

System.out.println("\nEnrollment no: " + eno_no + "\nName: " +


name + "\nCourse: " + course + "\nFee: " + fee);
}
}

9.Write a program that read the elements of a one dimensional


array print the sum of array elements.

// 9.Program
import java.util.*;
class SumOfArray
{
public static void main(String args[])
{
int sum=0;
int []array=new int[3];
Scanner sc=new Scanner(System.in);
System.out.println("Enter a element in a array: ");

for(int i=0;i<array.length;i++)
{
System.out.println("array ["+i+ "]=");
array[i]=sc.nextInt();
sum=sum+array[i];
}
System.out.println("Sum of array is "+sum);
}

}
10.Write a program to display the product of two diagonals
array. [Assume that the array size is 3x3]

//10.Program
import java.util.*;
class SumOfdiagonalArray
{
public static void main(String args[])
{
int i,j,ro,co;
Scanner sc=new Scanner(System.in);

System.out.println("Enter the number of rows");


ro=sc.nextInt();
System.out.println("Enter the number of column");
co=sc.nextInt();

int a[][]=new int[ro][co];


int b[][]=new int[ro][co];
int c[][]=new int[ro][co];

System.out.println("Enter a element of Matrix-1:")


for(i=0;i<ro;i++)
{
for(j=0;j<co;j++)
{
a[i][j]=sc.nextInt();
}
}

System.out.println("Enter a element of Matrix-2:");


for(i=0;i<ro;i++)
{
for(j=0;j<co;j++)
{
b[i][j]=sc.nextInt();
}
}

for(i=0;i<ro;i++)
{
for(j=0;j<co;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
//System.out.println();
}

System.out.println("Addition of Two Matrix:");


for(i= 0 ;i <ro ; i++)
{
for(j= 0; j<co ;j++)
{
System.out.print(c[i][j] + " ");
}
}
System.out.println();
}

11.Write a menu driven program using two dimensional arrays to


perform matrix addition, subtraction and multiplication.( Use
switch case)
The program asks the user to input the numbers of rows and
columns for matrix A and matrix B before entering the elements
of each array.

// 11.Program

import java.util.*;
import java.lang.*;
import java.io.*;

class MatrixOperation
{
public static void main(String[] args)
{
int ch;
Scanner sc = new Scanner(System.in);
System.out.print("1. Addition \n");
System.out.print("2. Substraction \n");
System.out.print("3. Multiplication \n");
System.out.print("4. Exit \n \n");
ch = sc.nextInt();

switch(ch)
{
case 1:
addition.add();
break;

case 2:
substraction.subtract();
break;

case 3:
multiplication.multiply();
break;

case 4:
System.out.println();
break;

default:
System.out.println("Invalid choice....");
break;
}
}
}

class addition{

static void add()


{
int i,j;
int a[][],b[][],c[][];
int row,col;
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Number Of Row:- ");
row = sc.nextInt();
System.out.println("Enter The Number Of Columns:- ");
col = sc.nextInt();

a = new int [row][col];


b = new int [row][col];

System.out.println("Enter The First Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
a[i][j] = sc.nextInt();
}
}

System.out.println("Enter The Second Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
b[i][j] = sc.nextInt();
}
}

c = new int [row][col];


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}

System.out.println("The Addition of Two Matrix are:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}
class substraction{
static void subtract()
{
int i,j;
int a[][],b[][],c[][];
int row,col;
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Number Of Row:- ");
row = sc.nextInt();
System.out.println("Enter The Number Of Columns:- ");
col = sc.nextInt();

a = new int [row][col];


b = new int [row][col];

System.out.println("Enter The First Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
a[i][j] = sc.nextInt();
}
}

System.out.println("Enter The Second Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
b[i][j] = sc.nextInt();
}
}

c = new int [row][col];


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
c[i][j] = a[i][j] - b[i][j];
}
}

System.out.println("The Addition of Two Matrix are:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}

class multiplication{
static void multiply()
{
int i,j;
int a[][],b[][],c[][];
int row,col;
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Number Of Row:- ");
row = sc.nextInt();
System.out.println("Enter The Number Of Columns:- ");
col = sc.nextInt();

a = new int [row][col];


b = new int [row][col];

System.out.println("Enter The First Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
a[i][j] = sc.nextInt();
}
}

System.out.println("Enter The Second Matrix:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
b[i][j] = sc.nextInt();
}
}

c = new int [row][col];


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
c[i][j] = a[i][j] * b[i][j];
}
}

System.out.println("The Addition of Two Matrix are:- ");


for (i=0;i<row;i++ )
{
for (j=0;j<col;j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
sc.close();
}
}

12.Create class Student which have following properties:


Data Members: EnrollmentNo, Name, Course, Marks of five
subjects, Total and percentage and Grade.
Methods: insert, percentageCalculation, gradeCalculation,
resultGeneration.
Write a program which will display students result according to
grade wise.
[Note: insert() is used for insertion which will call
percentageCalculation method; after calculating percentage it
will call gradeCalculation(); after calculating grade it will call
resultGeneration() for displaying the result of students. Use the
concept of “array of object”]
ANS
import java.util.Scanner;
class Student1{
public int eno;
public String name;
public String c;//course
public int m[] = new int[5];
public int t = 0;
public float p;
public String g;
public void insert(){
Scanner sc=new Scanner(System.in);
Scanner sc1=new Scanner(System.in);
System.out.println("Enter eno: ");
eno = sc.nextInt();
System.out.println("Enter name: ");
name = sc1.nextLine();
System.out.println("Enter course: ");
c = sc1.nextLine();
System.out.println("Enter the marks of 5 subjects: ");
for(int i=0; i<5; i++)
{
m[i]=sc.nextInt();;
t = t + m[i];
}
}
public void percent(){
p = t/5;
System.out.println("Percentage :- "+p);
}
public void grade(){
if(p>90){
g = "A+";
System.out.println("Grade "+g);
}
else if(p>80 && p<90){
g = "A";
System.out.println("Grade "+g);
}
else if(p>65 && p<80){
g = "B+";
System.out.println("Grade "+g);
}
else if(p>55 && p<65){
g = "B";
System.out.println("Grade "+g);
}
else if(p>45 && p<55){
g = "C";
System.out.println("Grade "+g);
}
else if(p>35 && p<45){
g = "D";
System.out.println("Grade "+g);
}
else{
g = "F";
System.out.println("Grade "+g);
}
}

}
class prac12{
public static void main(String args[]){
Student1 ob[] = new Student1[2];
ob[0] = new Student1();
ob[1] = new Student1();
System.out.println("Student 1:-\n");
ob[0].insert();
ob[0].percent();
ob[0].grade();
System.out.println("Student 2:-\n");
ob[1].insert();
ob[1].percent();
ob[1].grade();
}
}

13.Create class Product which have following properties:


Data Members: ProductNo, Name, quantity and price per
quantity.
Methods: purchase, sale and display.
Write a menu driven program which ask end user whether he/she
want to purchase, or sale product; according to the user choice
perform operation and make necessary updation in quantity.
Note: before giving choice to user insert minimum five product
information through constructor. (Use
the concept of array of object)

14.Write a program to input a string and print it in reverse order.

// 14.Program
import java.util.*;
import java.io.*;
import java.lang.*;

public class Reverse


{
public static void main(String[] args)
{
String s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter String:- ");
s = sc.next();

StringBuffer sb = new StringBuffer(s);


sb.reverse();
System.out.println(sb);
}
}
15.Write a program that creates string variables called Name, father‟s
name, Surname and myName. Using concatenation, assigns the value of
Name, father‟s name and surname into myName, and displays it on screen.

//program 15.
import java.util.*;
class StringConcatenation
{
public static void main(String args[])
{
String name, fname, surname, MyName;
Scanner sc=new Scanner(System.in);

System.out.println("Enter Name: ");


name=sc.next();
System.out.println("Enter Father's Name: ");
fname=sc.next();
System.out.println("Enter Surname: ");
surname=sc.next();
MyName = name+" "+fname+" "+surname;
System.out.println("\nMy name is "+MyName+".");
}
}

16.Write a program to input a sentence (with blank space) and display all
characters and their occurrence in inputted string.
i.e. LIRIL -> then output like following
I–2
L–2
R–1

//16 program

import java.util.*;
import java.lang.*;
import java.io.*;

public class CharacterOccurence


{
public static void main(String[] args)
{
String str = "aditya";
/*Scanner sc = new Scanner(System.in);
System.out.println("Enter a String or Sentence: ");
str = sc.next();*/
Occurence(str);
}

static final int MAX_CHAR = 256;


static void Occurence(String str)
{
int i,j,find=0;
char ch[];
// Create an array of size 256.
int count[] = new int[MAX_CHAR];
int len = str.length();
// Initialize array index count
for ( i=0 ; i<len ;i++ )
{
count[str.charAt(i)]++;
}
// Create array of given String size
ch = new char[str.length()];
for (i=0 ; i<len ;i++ )
{
ch[i] = str.charAt(i);
for (j=0 ; j<=i ;j++ )
{
if(str.charAt(i) == ch[j])
{
find++;
}
}

if (find == 1)
{
System.out.println("Number Of Occurence Of " +
str.charAt(i) + " is: " + count[str.charAt(i)]);
}
}
}
}
17.Create class ShapeArea which will calculate area of different
geographical shape like triangle, circle, square, rectangle, etc.
Write a program which will calculate and display the area of shapes using
the concept of method overloading.

//17.program

import java.util.*;
import java.lang.*;
import java.io.*;

public class ShapeArea


{
void calculate(int w,int l)
{
int r = w * l;
System.out.println("Area of Rectangle is " + r);
}

void calculate(int a)
{
double s = a * a;
System.out.println("Area of Square is " + s);
}

void calculate(double pi,int r)


{
double c = pi * r * r;
System.out.println("Area of Circle is " + c);
}

void calculate(double b,double h,double r)


{
double t = b*h/r;
System.out.println("Area of Triangle is " + t);
}

public static void main(String[] args)


{
ShapeArea obj = new ShapeArea();
obj.calculate(20,30);
obj.calculate(4);
obj.calculate(3.14,2);
obj.calculate(4,5,2);

18.Write a program which will use the concept of method overloading and
calculate volume of a Box. Box class have following properties:
Data Members:
Width
Height Depth Method: volume() having three argument
volume() having two argument
display()
Note: volume = (width*height*depth)

//18.program

import java.util.*;
import java.lang.*;

public class VolumeOfBox


{
int height,width,depth;
int v,m;

public static void main(String[] args)


{
VolumeOfBox obj = new VolumeOfBox();
obj.volume(2,2,2);
obj.volume(2,3);
obj.display();
}

void volume(int h,int w,int d)


{
height = h;
width = w;
depth = d;

v = h * w * d;
}
void volume(int h,int w)
{
height = h;
width = w;

m = h * w;
}

void display()
{
System.out.println("Volume of Box Is: " + v);
System.out.println("Volume Is: " + m);
}
}

19.Write a program to create class StringComparison in which data


members are str1 and str2 of static String type, methods of a class are
insert, comparison and display; insert and comparison are static method.
After insertion of a two string; call comparison method from insert method
which will check whether the string is equal or not after checking call
display method from comparison method for displaying appropriate result.

//program 19.
import java.io.*;
import java.lang.*;
import java.util.*;
class StringComparison
{
static String str1, str2;

public static void main(String args[])


{
insert();
}

static void insert()


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String1: ");
str1=sc.next();
System.out.println("Enter String2: ");
str2=sc.next();
comparision();
}

static void comparision()


{
System.out.println(str1.equals(str2));
display();
}

static void display()


{
if (str1.equals(str2))
{
System.out.println("\nBoth String are Equal..!");
}

else
{
System.out.println("\nBoth String are not Equal..!");
}
}
}

20.Create two class one is Friend and another is Buddy, Friend class has
data member like name and email-id, and Buddy class inherit the
properties of Friend class and it has data member like dob, mobile no and
address and do the following operation.
1. Create three constructor for base and derived class.
2. Insert data through derived class parameterized constructor.
3. Illustrate the use of this reference and Super.
Display all the information through parent class reference variable.

Ans 20)
class Friend{
public String name;
public String email;

public Friend(String name, String email){


this.name = name;
this.email = email;
}

public void displayFrind() {


System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.email);
}
}

public class Buddy extends Friend{


public String dob;
public long mno;
public String ad;

public Buddy(String name, String email, String dob, long mno, String
ad){
super(name, email);
this.dob = dob;
this.mno = mno;
this.ad = ad;
}

public void displayBuddy() {


System.out.println("Data of the Buddy class: ");
System.out.println("Name: "+this.name);
System.out.println("Email:: "+this.email);
System.out.println("DOB: "+this.dob);
System.out.println("Mobile no.: "+this.mno);
System.out.println("Address: "+this.ad);
}

public static void main(String args[]){


Buddy b = new Buddy("Yash","yashamin@gmail.com","24 dec
2000",123456789,"ABC");
b.displayBuddy();
}
}

21. Create three class Vehicle, TwoWheeler and


FourWheeler. Vehicle is a parent class of TwoWheeler and FourWheeler.
In Vehicle class data member is company name, and methods are input
and display. In TwoWheelers class, data members are name, type(gear,
non gear); and methods are input and display. In FourWheelers data
members are name, model no, fuel type; and methods are input and
display. Write a program which will input and display information of two
wheeler and four wheeler using the concept of method overriding.
Ans 21
class Vehicle
{
String company_name;
Vehicle(String c)
{
company_name = c;
}
void display()
{
System.out.println("company name: "+company_name);
}
}

class Twowheeler extends Vehicle


{
String name;
String type;
Twowheeler(String c,String n,String t)
{
super(c);
name = n;
type=t;
}
void display()
{
System.out.println("Two wheeler :- ");
super.display();
System.out.println("Name : " +name);
System.out.println("Type : " +type);
}
}

class Fourwheeler extends Vehicle


{
String name;
String fuel_type;
int m_no;

Fourwheeler(String c,String n,String f,int m)


{
super(c);
name=n;
fuel_type=f;
m_no=m;
}
void display()
{
System.out.println("Four wheeler car");
super.display();
System.out.println("Name : " +name);
System.out.println("fuel type : " +fuel_type);
System.out.println("model no: " +m_no);
}
}

class VehicleDemo
{
public static void main(String arg[])
{
Twowheeler t1;
Fourwheeler f1;
t1=new Twowheeler("Suzuki", "Access","Non-Gear");
f1=new Fourwheeler("Honda","Amaze","Petrol",4);
t1.display();
f1.display();
}
}
22. Create three class Employee, Teaching,
Nonteaching; In Employee class data members are employee no, name and
there are two abstract methods set and get. Teaching class inherit the
properties of Employee and its data members are course, designation and
salary. Nonteaching class inherits the properties of Employee class and its
data members are department, designation and salary. Write a program to
display employee information according to designation wise.
ANS 22
import java.util.*;

abstract class Employee{


int eno;
String name;

abstract void set();


abstract void get();
}

class Teaching extends Employee{


String course;
String designation;
int salary;

void set(){
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
System.out.println("Enter eno:- ");
super.eno = sc.nextInt();
System.out.println("Enter name:- ");
super.name = sc1.nextLine();
System.out.println("Enter course:- ");
this.course = sc1.nextLine();
System.out.println("Enter designation:- ");
this.designation = sc1.nextLine();
System.out.println("Enter salary:- ");
this.salary = sc1.nextInt();

void get(){
System.out.println("En no.:- "+super.eno);
System.out.println("Name:- "+super.name);
System.out.println("Course:- "+this.course);
System.out.println("designation:- "+this.designation);
System.out.println("salary:- "+this.salary);

}
}

class Non_Teaching extends Employee{


String department;
String designation;
int salary;

void set(){
Scanner sc = new Scanner(System.in);
Scanner sc1 = new Scanner(System.in);
System.out.println("Enter eno:- ");
super.eno = sc.nextInt();
System.out.println("Enter name:- ");
super.name = sc1.nextLine();
System.out.println("Enter department:- ");
this.department = sc1.nextLine();
System.out.println("Enter designation:- ");
this.designation = sc1.nextLine();
System.out.println("Enter salary:- ");
this.salary = sc1.nextInt();

void get(){
System.out.println("En no.:- "+super.eno);
System.out.println("Name:- "+super.name);
System.out.println("Course:- "+this.department);
System.out.println("designation:- "+this.designation);
System.out.println("salary:- "+this.salary);

}
}

class prac22
{
public static void main(String arg[])
{
Teaching t1;
Non_Teaching n;
t1=new Teaching();
n=new Non_Teaching();
System.out.println("Teaching class:- ");
t1.set();
t1.get();
System.out.println("Non Teaching class:- ");
n.set();
n.get();
}
}

23. Create two interface PrivateBank and


GovernmentBank and one class Customer.
PrivateBank interface have three methods newAccount, withdrawAmount
and depositeAmount. GovernmentBank have three methods newAccount,
withdrawAmount and depositeAmount. Customer class inherit the
properties of PrivateBank and GovernmentBank and have data members
like AccountNo, Name, and Amount and has method display.
Write a menu driven program to perform banking operations like open
account, withdraw and deposit amount for private as well as government
bank.

24. Create three interfaces and one class called Hockey, Cricket, Tennis
and Player respectively. Player class inherits the properties of Hockey,
Cricket and Tennis.
In Hockey; method is h(), in Cricket;method is c(),and in Tennis method
is t(); all the methods insert no of player required for playing the
particular game.
Player class have data members player_name and type_of_sport and
method insertInfo() and display().
Write a menu driven program which will ask user choice for the sports and
according to user choice call appropriate method to insert no of player
required. After getting the information of sports and no of player required
call insertInfo() which will take players name. After performing all the
necessary operation display information of sports and player in a proper
format.

25.Write a program which throws an exception whenever user enters a


string of five characters.

//25.program

import java.util.*;
import java.lang.*;

public class Exception


{
public static void main(String[] args)
{
try
{
String str;
Scanner sc = new Scanner(System.in);
System.out.println("Enter A String: ");
str = sc.next();

System.out.println(str.length());
char c = str.charAt(4);
c = str.charAt(4);
//System.out.println(c);
}

catch(StringIndexOutOfBoundsException e)
{
System.out.println("Can not Enter More Than Four
Character.");
}
}
}

26. Write a program which will take adhaar number from the user, if
adhaar number is not start with „I‟ then throw the exception. (Assume
that Adhaar number starts with „I‟, use the concept of user define
exception)

27. Write a program to create custom exception for bank that contain
fields accountno, and balance throw an exception for the following
condition:
a. If withdrawing amount is greater than actual amount.
If balance become less than 500 after withdrawing amount.

28. Define package mypackage with class Number.


Define following method for Number class.
1. To find factorial of given number.
2. To find sum of digit for given number 3. To find reverse number of
given number
4. To find sum of 1 to N.
Write class to test above package and its method.
ANS 28
package mypackage;

class Number{
public void Factorial(){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}

public void SumOfDigits(){


long n,sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number ");
n=sc.nextLong();
for(sum=0 ;n!=0 ;n/=10)
{
sum+=n%10;
}
System.out.println("Sum of digits "+sum);
}

public void ReverseNumbers(){


int num = 1234, reversed = 0;

while(num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

System.out.println("Reversed Number: " + reversed);


}

public void SumOfNaturalNumber(){


int i, num = 1000, sum = 0;
for(i = 1; i <= num; ++i)
{
sum = sum + i;
}
System.out.println("Sum of First 10 Natural Numbers is = " + sum);
}

29. Write a program that creates a user-define class called


CustomerFeedback containing members such as CutomerId, name,
Feedback, type of product.
Assume that five customers have given their feedback for the various
products. Prepare a list of customer feedback based on the type of the
product.
(Note: Use ArrayList to store different type of customer feedback.)

30. Write a java program which will insert data from the console and write
into file.

//30.program
import java.io.*;
import java.lang.*;
import java.util.*;

public class FileWriter


{
public static void main(String[] args) throws IOException
{
try
{
FileWriter w = new FileWriter("output.txt");
String str,no;
Console c = System.console();
System.out.println("Enter Name: ");
str = c.readLine();
System.out.println("Enter Number: ");
no = c.readLine();
System.out.println("Hello " + str + " And Your no is " + no);

w.write(str + no);
w.close();
System.out.println("Done.");
}

catch(IOException e)
{
e.printStackTrace();
}
}
}

31. Write a java program which will read data from the file and display on
console.
//31.PROGRAM
import java.util.Scanner;
import java.io.*;
public class JavaProgram
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);

/* enter filename with extension to open and read its content */


System.out.print("Enter File Name to Open (extension like file.txt) : ");
fname = scan.nextLine();

/* this will reference only one line at a time */

String line = null;


try
{
/* FileReader reads text files in the default encoding */

FileReader fileReader = new FileReader(fname);

/* always wrap the FileReader in BufferedReader */

BufferedReader bufferedReader=new
BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null)


{
System.out.println(line);
}

/* always close the file after use */

bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
32. Write a java program which will count total number of character, word
and line.
ANS 32
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WordCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;

int charCount = 0;

int wordCount = 0;

int lineCount = 0;

try
{

reader = new BufferedReader(new FileReader("sample.txt"));

String currentLine = reader.readLine();

while (currentLine != null)


{

lineCount++;

String[] words = currentLine.split(" ");

wordCount = wordCount + words.length;


for (String word : words)
{
//Updating the charCount

charCount = charCount + word.length();


}

currentLine = reader.readLine();
}

System.out.println("Number Of Chars In A File : "+charCount);

System.out.println("Number Of Words In A File : "+wordCount);

System.out.println("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

33. Write a java program which will read data from one file and store it
into another file.
ANS 33
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class prac33 {

public static void main(String[] args) {


try
{
boolean create=true;
Scanner KB=new Scanner(System.in);

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


String sfilename=KB.next();
File srcfile=new File(sfilename);
if(!srcfile.exists())
{
System.out.println("File Not Found..");
}
else
{
FileInputStream FI=new FileInputStream(sfilename);
System.out.print("Enter Target File Name:");
String tfilename=KB.next();
File tfile=new File(tfilename);
if(tfile.exists())
{
System.out.print("File Already Exist OverWrite it..Yes/No?:");
String confirm=KB.next();
if(confirm.equalsIgnoreCase("yes"))
{
create=true;
}
else
{
create=false;
}
}
if(create)
{
FileOutputStream FO=new FileOutputStream(tfilename);
int b;
//read content and write in another file
while((b=FI.read())!=-1)
{
FO.write(b);
}
System.out.println("\nFile Copied...");
}
FI.close();
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}

34. Write a program which accept name from the user and display one by
one character of that name using thread sleep method.
ANS

import java.io.*;

class prac34
{
public static void main(String[] args)throws IOException
{
boolean stop=false;
String str="Sreedhar Practice seassion";

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


{
char ch=str.charAt(i);
String c=String.valueOf(ch);
g.drawString("\t"+c,10,100);
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
}
if (stop)
{
return;
}
}
}

35. Write a program to create a timer using thread(Make use of sleep()


method).

ANS 35

import java.util.concurrent.*;

class GFG {
public static void main(String args[])
{
// Get time to sleep
long timeToSleep = 10L;

// Create a TimeUnit object


TimeUnit time = TimeUnit.SECONDS;

try {

System.out.println("Going to sleep for "


+ timeToSleep
+ " seconds");

// using sleep() method


time.sleep(timeToSleep);

System.out.println("Slept for "


+ timeToSleep
+ " seconds");
}

catch (InterruptedException e) {
System.out.println("Interrupted "
+ "while Sleeping");
}
}
}
36. Write a program in Java to launch 5 threads. Each thread increments a
counter variable. Display value of thread using the concept of
synchronization.
ANS
public class Counter
{

static Thread[] threads = new Thread[5];


public static void main(String[] args)
{
Count c = new Count();
for(int i=0;i<5;i++)
{
threads[i] = new Thread(c);
threads[i].start();
}

}
}

public class Count implements Runnable {


int n=1;

public void run() {


System.out.println(n++);
}

public void showOutput(){


System.out.println(n++);
}

}
37. Write a program to create an applet which displays the following
message. Welcome
to Java. Above three line must be displayed in three different colours style.
Ans

import java.awt.Graphics;
import java.applet.Applet;
publicclass prac38 extends Applet
{
publicvoid paint(Graphics g)
{
g.drawString("Welcome",400,200);
g.drawString("to",400,300);
g.drawString("java",400,400);
}
}

38. Write a program to create an applet and draw different shapes like
rectangle, circle, oval and line with different colours.

// 38.Program
//appletviewer FirstApplet.java
import java.applet.Applet;
import java.awt.Graphics;
import java.util.*;
import java.io.*;

public class FirstApplet extends Applet{

public void paint(Graphics g)


{
g.setColor(Color.red);
g.drawString("Welcome",550, 550);
g.drawLine(20,30,20,300);

g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);

g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);

g.drawCircle(90,150,30,30,30,270);
g.fillCircle(270,150,30,30,0,180);
}
}

/*
<applet code="FirstApplet" height="300" width="500"></applet>
*/
39. Write a program to design simple calculator using applet.

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

public class AppletCalculator extends Applet implements ActionListener


{
Label l1,l2,l3;
TextField t1,t2;
Button b1,b2,b3,b4;

public void init()


{
setLayout(new FlowLayout());

l1=new Label("First Number:");


t1=new TextField(20);

l2=new Label("Second Number:");


t2=new TextField(20);

b1=new Button("Add");
b2=new Button("Sub");
b3=new Button("Mul");
b4=new Button("Div");

l3=new Label("Result");

add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(b3);
add(b4);
add(l3);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
Double num1=Double.parseDouble(t1.getText());
Double num2=Double.parseDouble(t2.getText());
if(ae.getSource()==b1)
{
Double value=num1+num2;
l3.setText(""+value);
}
if(ae.getSource()==b2)
{
Double value=num1-num2;
l3.setText(""+value);
}
if(ae.getSource()==b3)
{
Double value=num1*num2;
l3.setText(""+value);
}
if(ae.getSource()==b4)
{
Double value=num1/num2;
l3.setText(""+value);
}
}
}

40. Write a program to design email registration form using applet.


Ans
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class loginform extends Frame implements ActionListener
{
Label l1=new Label("User name : ");//OBJECT CREATE
Label l2=new Label("Surname : ");//OBJECT CREATE
Label l3=new Label(" ");//OBJECT CREATE
TextField t1=new TextField();//OBJECT CREATE
TextField t2=new TextField();//OBJECT CREATE
Button b=new Button("submit");//OBJECT CREATE
public loginform()
{
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);
l1.setBounds(20,45,70,20);//set co-ordinates
t1.setBounds(180,45,200,20);
l2.setBounds(20,95,70,20);
t2.setBounds(180,95,200,20);
b.setBounds(150,150,100,50);
b.addActionListener(this);
addWindowListener(new A());
}
public void actionPerformed(ActionEvent e)
{
l3.setText("SUBMITTED "+t1.getText());
}
public static void main(String s[])
{
loginform l=new loginform();
l.setSize(new Dimension(400,400));
l.setTitle("Login");
l.setVisible(true);
}//end of main
}//end of class loginform
class A extends WindowAdapter
{
public A(){}
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}//end of class A

You might also like