Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Java File

The document contains a practical file submitted by a student for their Java programming lab course. It includes 53 questions covering Java programming concepts like simple interest calculation, pattern printing, arrays, classes, inheritance, exceptions, threads, databases and GUI programming.

Uploaded by

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

Java File

The document contains a practical file submitted by a student for their Java programming lab course. It includes 53 questions covering Java programming concepts like simple interest calculation, pattern printing, arrays, classes, inheritance, exceptions, threads, databases and GUI programming.

Uploaded by

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

Practical File on

Java Programming

Subject Title: Practical VIII - Java Lab


Subject code: BCA 272

Submitted to Submitted by
Mr. Ashish Kumar Nayyar Deepanshi Mendiratta
Enrollment No: 05413702022

Institute of Information Technology & Management


D29, Institutional Area, Janakpuri, New Delhi-58
(Batch 2022-2025)
05413702022 Deepanshi Mendiratta

Index
Page Date of Faculty
Sr. No. Problem Statement
No. completion Sign.
1. Write a program to compute Simple Interest.

2. Write a program to compute the area of a circle.

3. Write a program to calculate average of all


multiples of 7 in a given range.
4. Write a program to print following patterns
i.) Ii.)
1 2 3 4 5 @
6 7 8 9 @ @
10 11 12 @ @ @
13 14 @ @ @ @
15 @ @ @ @ @
5. Write a program to print prime numbers in a given
range.
6. WAP that accepts number as Command line
arguments.
7. Write program that randomly generates a number
and checks whether it is prime or not.
8. Write program that randomly generates a number
from a range 10-99 and checks whether it is
Armstrong or not.
9. Write a program to insert an array and print those
elements using command line arguments.
10. Write a program to initialize and print the
elements of an array.
11. Write a program to sort an array in ascending and
descending order.
12. WAP to perform linear search on an Array of 5
integers.
13. WAP to perform binary search on an Array of 5
integers.
14. WAP to display smallest element of an Array of 5
integers.
15. WAP to display difference between smallest and
largest elements of an Array of 5 integers.
16. Write a program to perform following Matrix
operations using arrays.
i.) Addition
ii.) Multiplication
17. Write a program to demonstrate the working of
any Ten String class functions.
18. WAP to extract surname from complete name

19. Write a program to create a class called


StringDemo and declare three strings and use

2|Page
05413702022 Deepanshi Mendiratta

functions like length, charAt and equals on them.


20. Write a program to create a class student add
enrollment number name and percentage as data
fields. Add constructors and other necessary
functions to the class.
21. Write a program to create a class student add
enrollment number name and percentage as data
fields. Add constructors and other necessary
functions to the class.
Add function to perform name based linear search
on an array of 5 objects of student class.
22. Write a program to create a class called Use Static
and declare some static variables, a static method
that will print those variables and static block
which will perform some operation on that
variable.
23. Write a program to create a class Add that will add
to numbers by using a default constructor.
24. Write a program to create a class called triangle
with base and height as the attributes and
calculate its area using parameterized constructor.
25. Write a program to create a class called Rectangle
and calculate its area using this keyword.
26. Write a program to create a class called Box with
instance variables width, height and depth. Create
another class BoxWeight which inherits class Box
with an additional instance variable weight.
Compute the volume of the box using inheritance.
27. Implement the above program using super
keyword.
28. Create a class Figure and its 2 subclasses Rectangle
and Triangle and calculate its area using dynamic
method dispatch.
29. Implement the above program using abstract
classes by making Figure class abstract.
30. Write relevant programs to show the usage of final
keyword with class, variables and methods in java.
31. Write relevant programs showing the usage of
package and access protection in java also show
the concept of importing a package
32. Write a program to implement stacks using
interfaces.
33. Write a program to implementing nesting of
interface.
34. WAP that throws user defined exception if age of
voter is less than 18.
35. WAP that throws user defined exceptions if stack is
full or is empty.
36. Write a program declaring a Java class called
SavingsAccount with members ``accountNumber``
and ``Balance``. Provide member functions as

3|Page
05413702022 Deepanshi Mendiratta

``depositAmount ()`` and ``withdrawAmount ()``. If


user tries to withdraw an amount greater than
their balance then throw a user-defined exception
if bank balance drops below 1000 due to any
transaction.
37. Write relevant programs to show the concept of
creating Thread through thread class and Runnable
interfaceWAP to print multiples of 2,3,4
simultaneously.
38. WAP to show that high priority thread gets more
CPU attention than a low priority thread.
39. Write relevant programs to show the concept of
thread synchronization and inter-thread
communication.
40. Program in java to show the connectivity of java
with the database using different SQL statement.
41. WAP to insert a record in database.

42. WAP to create a table in database via java.

43. WAP that updates some records.

44. Program that displays the life cycle of the Applet


and other relevant programs that shows the
implementation of Applets in java.
45. Write Programs to draw different figures using
AWT.
46. Write programs to add label, Buttons, Textfield, list
etc using AWT.
47. Create a swing application by building a login
window to check user name and password using
text fields and command buttons
48. Create 3 control boxes for font name, size and
style, change font of the text according to user
selection.
49. Write a program using layout Manager to add
different controls on a frame.
50. Program to demonstrate different event handler.

51. Working with Graphics, colours and fonts in AWT.

52. Write a program to implement Swing 3 function


calculator.
53. Create a Swing login window to check user name
and password using text fields and command
buttons
54. Create a swing application with 3 control boxes for
font name, size and style, change font of the text
according to user selection.
55. Write program that uses swings to display
combination of RGB using 3 scrollbars.

4|Page
05413702022 Deepanshi Mendiratta

56. Write a swing application that uses atleast 5 swing


controls .

PRACTICAL NO – 1

Ques 1) Write a program to compute Simple Interest.


import java.io.*;

class Simpleint

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

int p,r,t;

float a;

BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter p,r and t");

p=Integer.parseInt(in1.readLine());

r=Integer.parseInt(in1.readLine());

t=Integer.parseInt(in1.readLine());

a=(float)p*r*t/100;

System.out.println("average= "+(a));}}

OUTPUT:

5|Page
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 2

Ques 2) Write a program to compute the area of a circle.


import java.io.*;
class areacir
{
public static void main(String args[])throws IOException
{
int r;
float a,pie=3.14f;
BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter r");
r=Integer.parseInt(in1.readLine());
a=(float)pie*r*r;
System.out.println("average= "+(a));}}

OUTPUT:

6|Page
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 3

Ques 3) Write a program to calculate average of all multiples of 7 in a


given range.
import java.io.*;

class Avgo7

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

{int lb,ub,i,sum=0;

int ctr=0;

float avg;

BufferedReader in1=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter lb and ub");

lb=Integer.parseInt(in1.readLine());

ub=Integer.parseInt(in1.readLine());

for(i=lb;i<=ub;i++)

{if(i%7==0)

{ctr++;

sum=sum+i;}}

avg=(float)sum/ctr;

System.out.println("average= "+(avg));}}

OUTPUT:

7|Page
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 4

Ques 4) Write a program to print following patterns

i.) ii.)

1 2 3 4 5 @

6 7 8 9 @ @

10 11 12 @ @ @

13 14 @ @ @ @

15 @ @ @ @ @
i) public class NumberPattern

public static void main(String[] args)

int rows = 5;

int count = 1;

for (int i = 1; i <= rows; i++)

for (int j = 1; j <= i; j++)

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

8|Page
05413702022 Deepanshi Mendiratta

count++;

System.out.println();

} } }

ii) public class PatternPrinter

public static void main(String[] args)

int rows = 5;

printPattern(rows); }

static void printPattern(int rows)

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

for (int j = 0; j < rows - i - 1; j++)

System.out.print(" ");

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

if (k == i)

System.out.print("@");

9|Page
05413702022 Deepanshi Mendiratta

else {

System.out.print("@ "); } }

System.out.println(); } }}

PRACTICAL NO – 5

Ques 5) Write a program to print prime numbers in a given range.


public class Main

public static void main (String[] args)

int lower = 1, upper = 20;

for (int i = lower; i <= upper; i++)

if (isPrime (i))

System.out.println (i);

static boolean isPrime (int n)

int count = 0;

if (n < 2)

return false;

for (int i = 2; i < n; i++)

{ if (n % i == 0)

return false; }

return true;

10 | P a g e
05413702022 Deepanshi Mendiratta

}}

OUTPUT:

PRACTICAL NO – 6

Ques 6) WAP that accepts number as Command line arguments.


class FirstProgram

public static void main(String args[])

int n1=0;

n1=Integer.parseInt(args[0]);

System.out.println("05413702022");

System.out.println("Deepanshi Mendiratta");

System.out.println("Number Entered is "+(n1));

}}

OUTPUT:

11 | P a g e
05413702022 Deepanshi Mendiratta

12 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 7

Ques 7) Write program that randomly generates a number and checks


whether it is prime or not.
import java.util.Random;
public class J7
{ static boolean isPrime(int n)
{ int i;
if( n==0||n==1){ return false; }
else
{for( i=2; i<n/2; i++)
{if( n%i==0){ return false; } } } return true; }
public static void main(String args[])
{ boolean flag;
Random rd = new Random();
int num = rd.nextInt(100);
System.out.println("The random number is "+num);
if( isPrime(num)){System.out.println(num+" is a prime number."); }
else{System.out.println(num+" is not a prime number."); }
System.out.println("05413702022");
System.out.println("Deepanshi Mendiratta"); }}

13 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 8

Ques 8) Write program that randomly generates a number from a range


10-99 and checks whether it is Armstrong or not.
import java.util.Random;

public class ArmstrongRandom {

static boolean isArmstrong(int n) {

int originalNumber = n;

int numDigits = String.valueOf(n).length();

int sum = 0;

while (n > 0) {

int digit = n % 10;

sum += Math.pow(digit, numDigits);

n /= 10; }

return sum == originalNumber; }

public static void main(String[] args) {

Random rd = new Random();

int num = rd.nextInt(90) + 10;

System.out.println("The random number is " + num);

if (isArmstrong(num)) {

System.out.println(num + " is an Armstrong number."); }

else {

System.out.println(num + " is not an Armstrong number."); }

System.out.println("Deepanshi"); System.out.println("05413702022"); }}

14 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 9

Ques 9) Write a program to insert an array and print those elements


using command line arguments.
class java9

public static void main(String args[])

int n1,n2,n3,n4;

n1=Integer.parseInt(args[0]);

n2=Integer.parseInt(args[1]);

n3=Integer.parseInt(args[2]);

n4=Integer.parseInt(args[3]);

int[] myArray=new int[]{n1,n2,n3,n4};

System.out.println("05413702022");

System.out.println("Deepanshi ");

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

System.out.println(myArray[i]);

15 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 10

Ques 10) Write a program to initialize and print the elements of an array.
class java10

public static void main(String args[])

System.out.println("05413702022");

System.out.println("Deepanshi");

int[] myArray = new int[]{12,32,93};

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

System.out.println(myArray[i]);

}}

16 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 11

Ques 11) Write a program to sort an array in ascending and descending


order.
import java.util.Arrays;

import java.util.Collections;

class ArraySort {

public static void main(String[] args) {

Integer[] arr = { 5, 2, 1, 8, 10 };

Arrays.sort(arr, Collections.reverseOrder());

System.out.println("05413702022");

System.out.println("Deepanshi");

System.out.print("descending order-");

for (int values : arr) {

System.out.print(values + ", ");

System.out.println("");

Arrays.sort(arr);

System.out.print("ascending order-");

for (int values : arr) {

System.out.print(values + ", ");

} } }

17 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 12

Ques 12) WAP to perform linear search on an Array of 5 integers.


public class Java12{

public static int Java12(int[] arr, int key){

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

if(arr[i] == key){

return i;

return -1;

public static void main(String a[]){

int[] a1= {10,20,30,50,70};

int key = 50;

System.out.println("05413702022");

System.out.println("Deepanshi");

System.out.println(key+" is found at index: "+Java12(a1, key));

} }

18 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 13

Ques 13) WAP to perform binary search on an Array of 5 integers.


class J13{

public static void J13(int arr[], int first, int last, int key){

int mid = (first + last)/2;

while( first <= last ){

if ( arr[mid] < key ){

first = mid + 1;

}else if ( arr[mid] == key ){

System.out.println("Element is found at index: " + mid);

break;

}else{

last = mid - 1; }

mid = (first + last)/2; }

if ( first > last ){ System.out.println("Element is not found!"); } }

public static void main(String args[]){

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

int key = 30;

System.out.println("05413702022");

System.out.println("Deepanshi");

int last=arr.length-1;

J13(arr,0,last,key); }}

19 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 14

Ques 14) WAP to display smallest element of an Array of 5 integers.


public class J14 {

public static void main(String[] args) {

int [] arr = new int [] {25, 11, 7, 75, 56};

int min = arr[0];

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

if(arr[i] <min)

min = arr[i];

System.out.println("05413702022");

System.out.println("Deepanshi");

System.out.println("Smallest element present in given array: " + min);

20 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 15

Ques 15) WAP to display difference between smallest and largest elements
of an Array of 5 integers.
import java.util.Arrays;

public class J15{

public static void main(String[] args) {

int[] array_nums = {5, 6, 2, 4, 9};

System.out.println("Original Array: " + Arrays.toString(array_nums));

int max_val = array_nums[0];

int min = array_nums[0];

for (int i = 1; i < array_nums.length; i++) {

if (array_nums[i] > max_val)

max_val = array_nums[i];

else if (array_nums[i] < min)

min = array_nums[i]; }

System.out.println("05413702022");

System.out.println("Deepanshi");

System.out.println("Difference between the largest and smallest values: " + (max_val -


min));

21 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 16

Ques 16) Write a program to perform following Matrix operations using


arrays.
i.) Addition

public class MatrixAddition{

public static void main(String args[]){

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

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

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

System.out.println("Deepanshi") ;

System.out.println("05413702022") ;

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

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

c[i][j]=a[i][j]+b[i][j];

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

System.out.println();}

}}

ii.) Multiplication

public class MatrixMultiplication{

public static void main(String args[]){

int a[][]={{1,1,1},{2,2,2},{3,3,3}};

int b[][]={{1,1,1},{2,2,2},{3,3,3}};

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

22 | P a g e
05413702022 Deepanshi Mendiratta

System.out.println("Deepanshi");

System.out.println("05413702022");

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

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

c[i][j]=0;

for(int k=0;k<3;k++)

{ c[i][j]+=a[i][k]*b[k][j]; }

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

System.out.println(); }

}}

23 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 17

Ques 17) Write a program to demonstrate the working of any Ten String
class functions.
import java.io.*;

public class StringFunctions {

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

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Deepanshi");System.out.println("05413702022");

System.out.println("Enter a string:");

String str = reader.readLine();

int length = str.length();

System.out.println("1. Length of the string: " + length);

if (length > 7)

{ char charAtIndex = str.charAt(7);

System.out.println("2. Character at index 7: " + charAtIndex); }

else{ System.out.println("2. String is too short to retrieve character at index 7."); }

if (length > 7)

{ String substring = str.substring(7);

System.out.println("3. Substring from index 7: " + substring); }

else { System.out.println("3. String is too short to create a substring."); }

int indexOfSpace = str.indexOf(" ");

System.out.println("4. Index of first space: " + indexOfSpace);

boolean containsHello = str.contains("Hello");

System.out.println("5. Does the string contain 'Hello'? " + containsHello);

String upperCase = str.toUpperCase();

System.out.println("6. Uppercase string: " + upperCase);

String lowerCase = str.toLowerCase();

24 | P a g e
05413702022 Deepanshi Mendiratta

System.out.println("7. Lowercase string: " + lowerCase);

String replacedString = str.replace("Hello", "Hi");

System.out.println("8. String after replacement: " + replacedString);

String stringWithWhitespace = " " + str + " ";

String trimmedString = stringWithWhitespace.trim();

System.out.println("9. Trimmed string: '" + trimmedString + "'");

System.out.println("Enter a delimiter to split the string:");

String delimiter = reader.readLine();

String[] splitArray = str.split(delimiter);

System.out.println("10. Split array:");

for (String s : splitArray) { System.out.println(" " + s.trim()); }}}

25 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 18

Ques 18) WAP to extract surname from complete name.


import java.io.*;

public class SurnameExtractor {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {

System.out.println("Enter your complete name:");

String fullName = reader.readLine();

String[] nameParts = fullName.split("\\s+"); // Splitting by whitespace

String surname = nameParts[nameParts.length - 1]; // Last part is assumed to be surname

System.out.println("Your surname is: " + surname);

reader.close();

catch (IOException e) {

System.out.println("An error occurred while reading input.");

e.printStackTrace();

26 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 19

Ques 19) Write a program to create a class called StringDemo and declare
three strings and use functions like length, charAt and equals on them.
import java.io.*;

public class StringDemo {

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

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Deepanshi");

System.out.println("05413702022");

System.out.print("Enter the first string: ");

String str1 = reader.readLine();

System.out.print("Enter the second string: ");

String str2 = reader.readLine();

System.out.print("Enter the third string: ");

String str3 = reader.readLine();

// Display the length of each string

System.out.println("Length of str1: " + str1.length());

System.out.println("Length of str2: " + str2.length());

System.out.println("Length of str3: " + str3.length());

// Access individual characters using charAt

System.out.println("Character at index 0 in str1: " + str1.charAt(0));

System.out.println("Character at index 3 in str2: " + str2.charAt(3));

// Check if str1 is equal to str2

if (str1.equals(str2)) {

System.out.println("str1 is equal to str2");

} else {

System.out.println("str1 is not equal to str2");

27 | P a g e
05413702022 Deepanshi Mendiratta

if (str1.equals(str3)) {

System.out.println("str1 is equal to str3");

} else {

System.out.println("str1 is not equal to str3");

reader.close();

}}

28 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 20

Ques 20) Write a program to create a class student add enrollment number
name and percentage as data fields. Add constructors and other necessary
functions to the class.
import java.io.*;

public class Student{

int enrollNo;

String name;

double per;

public Student(){}

public Student(int enrollNo, String name, double per){

this.enrollNo=enrollNo;

this.name=name;

this.per=per;

public int getEnrollNo(){

return enrollNo;

public String getName(){

return name;

public double getPercentage(){

return per;

public void setEnrollNo(int enrollNo){

this.enrollNo=enrollNo;

29 | P a g e
05413702022 Deepanshi Mendiratta

public void setName(String name){

this.name=name;

public void setPercentage(double per){

this.per=per;

public void display(){

System.out.println("Entrollment No.: "+enrollNo);

System.out.println("Name: "+name);

System.out.println("Percentage: "+per+"%");

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

Student s1=new Student(54, "Deepanshi", 95.85);

System.out.println("-------STUDENT DETAILS-------");

s1.display();

30 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 21

Ques 21) Write a program to create a class student add enrollment number
name and percentage as data fields. Add constructors and other necessary
functions to the class. Add function to perform name based linear search
on an array of 5 objects of student class.
import java.io.*;

public class Student{

int enrollNo;

String name;

double per;

public Student(){}

public Student(int enrollNo, String name, double per){

this.enrollNo=enrollNo;

this.name=name;

this.per=per; }

public int getEnrollNo(){

return enrollNo; }

public String getName(){

return name; }

public double getPercentage(){

return per; }

public void setEnrollNo(int enrollNo){

this.enrollNo=enrollNo; }

public void setName(String name){

this.name=name; }

public void setPercentage(double per){

this.per=per; }

public void displayStudentInfo(){

31 | P a g e
05413702022 Deepanshi Mendiratta

System.out.println("Entrollment No.: "+enrollNo);

System.out.println("Name: "+name);

System.out.println("Percentage: "+per+"%"); }

public static void displayStudentDetails(Student[] students){

System.out.println();

System.out.println("-------STUDENT DETAILS-------");

for(Student stud:students){

stud.displayStudentInfo(); }}

public static Student searchStudent(Student[] students, String key){

for(Student stud:students){

if(stud.getName().equals(key)){

return stud; }}

return null; }

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

int enroll, i, n=3;

String name, target;

double per;

Student[] studentArr=new Student[n];

Student result;

BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));

for(i=0; i<studentArr.length; i++)

{ System.out.println("Enter details for Student " + (i + 1));

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

enroll=Integer.parseInt(rd.readLine());

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

name=rd.readLine();

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

32 | P a g e
05413702022 Deepanshi Mendiratta

per=Double.parseDouble(rd.readLine());

studentArr[i]=new Student(enroll, name, per); }

displayStudentDetails(studentArr);

System.out.print("Enter the name of the student to be searched: ");

target=rd.readLine();

result=searchStudent(studentArr, target);

if(result!=null)

{ System.out.println();

System.out.println("Student found:");

result.displayStudentInfo(); }

else{

System.out.println("Student with name '" + target + "' not found."); }

System.out.println("\nDeepanshi");

System.out.println("05413702022"); }}

33 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 22

Ques 22) Write a program to create a class called Use Static and declare
some static variables, a static method that will print those variables and
static block which will perform some operation on that variable.
import java.io.*;

class UseStatic

{ static int num1=50;

static double num2;

static

{ num2=num1*2;

num1++;

static void display()

{ System.out.println("Static variable 1 (num1): "+num1);

System.out.println("Static variable 2 (num2): "+num2);

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

{ display();

System.out.println("Deepanshi");

System.out.println("05413702022");

34 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 23

Ques 23) Write a program to create a class Add that will add to numbers
by using a default constructor.
import java.io.*;

class Add

{ int num1, num2, sum;

public Add()throws IOException

BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter first number: ");

num1=Integer.parseInt(rd.readLine());

System.out.print("Enter second number: ");

num2=Integer.parseInt(rd.readLine());

sum=num1+num2;

System.out.println("Sum: "+sum);

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

{ Add ad1=new Add();

System.out.println("Deepanshi");

System.out.println("05413702022");

35 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 24

Ques 24) Write a program to create a class called triangle with base and
height as the attributes and calculate its area using parameterized
constructor.
import java.io.*;

public class Triangle {

private double base;

private double height;

public Triangle(double base, double height) {

this.base = base;

this.height = height; }

public double calculateArea() {

return 0.5 * base * height; }

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

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Deepanshi");System.out.println("05413702022");

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

double base = Double.parseDouble(reader.readLine());

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

double height = Double.parseDouble(reader.readLine());

Triangle triangle = new Triangle(base, height);

double area = triangle.calculateArea();

System.out.println("Area of the triangle: " + area);

reader.close();}}

36 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 25

Ques 25) WAP to create a class called Rectangle and calculate its area
using this keyword.
import java.io.*;

public class Rectangle {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width; }

public double calculateArea() {

return this.length * this.width; }

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

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Deepanshi");System.out.println("05413702022");

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

double length = Double.parseDouble(reader.readLine());

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

double width = Double.parseDouble(reader.readLine());

Rectangle rectangle = new Rectangle(length, width);

double area = rectangle.calculateArea();

System.out.println("Area of the rectangle: " + area);

reader.close(); }}

37 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 26

Ques 26) Write a program to create a class called Box with instance
variables width, height and depth. Create another class BoxWeight which
inherits class Box with an additional instance variable weight. Compute the
volume of the box using inheritance.
import java.io.*;

class Box

{float width, height, depth;

Box()

{ width = 0;

height = 0;

depth = 0; }

Box(float w, float h, float d)

{ width = w;

height = h;

depth = d;

}}

class BoxWeight extends Box

float weight;

BoxWeight()

super();

weight = 0; }

BoxWeight(float w, float h, float d, float wt)

{ super(w,h,d);

weight = wt;}

void volume()

38 | P a g e
05413702022 Deepanshi Mendiratta

System.out.println("Width of the box: "+width);

System.out.println("Height of the box: "+height);

System.out.println("Depth of the box: "+depth);

System.out.println("Volume of the box: "+width*height*depth);

}}

class Demonstration

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

System.out.println("Deepanshi Mendiratta 05413702022\


n********************************");

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

float width, height, depth;

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

width = Float.parseFloat(input.readLine());

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

height = Float.parseFloat(input.readLine());

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

depth = Float.parseFloat(input.readLine());

BoxWeight box = new BoxWeight(width, height, depth, 100.0f);

box.volume(); } }

39 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 27

Ques 27) Implement the above program using super keyword.


import java.io.*;

class Box

float width, height, depth;

Box()

width = 0;

height = 0;

depth = 0;

Box(float w, float h, float d)

width = w;

height = h;

depth = d;

}}

class BoxWeight extends Box

float weight;

BoxWeight()

{ super();

weight = 0;

BoxWeight(float w, float h, float d, float wt)

{ super(w,h,d);

40 | P a g e
05413702022 Deepanshi Mendiratta

weight = wt; }

void volume()

System.out.println("Width of the box: "+width);

System.out.println("Height of the box: "+height);

System.out.println("Depth of the box: "+depth);

System.out.println("Volume of the box: "+width*height*depth);

}}

class Demonstration1

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

System.out.println("Deepanshi Mendiratta 05413702022");

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

float width, height, depth;

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

width = Float.parseFloat(input.readLine());

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

height = Float.parseFloat(input.readLine());

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

depth = Float.parseFloat(input.readLine());

BoxWeight box = new BoxWeight(width, height, depth, 100.0f);

box.volume(); } }

41 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 28

Ques 28) Create a class Figure and its 2 subclasses Rectangle and Triangle
and calculate its area using dynamic method dispatch.
abstract class Figure

abstract double calculateArea();

class Rectangle extends Figure

double length;

double width;

Rectangle(double length, double width)

this.length = length;

this.width = width;

double calculateArea(){

return length*width;

}}

class Triangle extends Figure

double base;

double height;

Triangle(double base, double height){

this.base = base;

this.height = height;

42 | P a g e
05413702022 Deepanshi Mendiratta

double calculateArea(){

return 0.5*(base*height);

}}

class Demo

public static void main(String args[])

System.out.println("Deepanshi Mendiratta 05413702022");

Rectangle r1 = new Rectangle(10, 20);

System.out.println("Rectangle Area: "+r1.calculateArea());

Triangle t1 = new Triangle(10, 20);

System.out.println("Triangle Area: "+t1.calculateArea());

}}

43 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 29

Ques 29) Implement the above program using abstract classes by making
Figure class abstract.
abstract class Figure

abstract double calculateArea();

class Rectangle extends Figure

double length;

double width;

Rectangle(double length, double width)

this.length = length;

this.width = width;

double calculateArea(){

return length*width;

}}

class Triangle extends Figure

double base;

double height;

Triangle(double base, double height){

this.base = base;

this.height = height;

44 | P a g e
05413702022 Deepanshi Mendiratta

double calculateArea(){

return 0.5*(base*height);

}}

class Demo

public static void main(String args[])

System.out.println("Deepanshi Mendiratta 05413702022");

Rectangle r1 = new Rectangle(5, 10);

System.out.println("Rectangle Area: "+r1.calculateArea());

Triangle t1 = new Triangle(7, 20);

System.out.println("Triangle Area: "+t1.calculateArea());

}}

45 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 30

Ques 30) Write relevant programs to show the usage of final keyword with
class, variables and method in java.
final class FinalClass {

final int MAX_VALUE = 100;

final void display() {

System.out.println("Displaying from FinalClass");

}}

class SecondClass extends FinalClass

void display(){

System.out.println("Displaying from SecondClass");

}}

class J30 {

public static void main(String[] args) {

System.out.println("Deepanshi Mendiratta 05413702022 ");

FinalClass finalObject = new FinalClass();

finalObject.MAX_VALUE = 30;

System.out.println("Maximum value: " + finalObject.MAX_VALUE);

46 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 31

Ques 31) Write a relevant program to show usage of package and access
protection in java, also show the concept of importing a package.
Demonstration.java

import mypckg.DemoPckg;

class Demonstration

{ public static void main(String args[])

{ System.out.println("Deepanshi Mendiratta 05413702022");

DemoPckg demo = new DemoPckg();

System.out.println("add(10, 30): ");

demo.add(10, 30);

demo.var = 40;}}

DemoPckg.java

package mypckg;

public class DemoPckg {

protected int sum = 0;

public void add(int a, int b)

{System.out.println("This is a public function in DemoPckg");

sum = a+b;

System.out.println("Protected Variable sum: "+sum); }}

Before changing sum variable from Demonstration class

After changing sum variable from Demonstration class

47 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 32

Ques 32) Write a relevant program to show usage of package and access
protection in java, also show the concept of importing a package.
interface Stack

{void push(int item);

int pop();

void display();}

class MyStack implements Stack

private int top;

private final int MAX_SIZE = 20 ;

private int stack[];

MyStack()

{ stack = new int[MAX_SIZE];

top = -1; }

public void push(int item)

{ if(top == MAX_SIZE-1)

{ System.out.println("Stack Overflow");

return;}

stack[++top] = item;}

public int pop()

{ if(top == -1)

{ System.out.println("Stack Underflow");

return -1;}

return stack[top--];

} public void display()

{ if(top == -1)

48 | P a g e
05413702022 Deepanshi Mendiratta

{ System.out.println("Stack is empty");}

else

System.out.println("Stack: ");

for(int i=top; i>=0; i--){

System.out.print(stack[i]+" | "); }

System.out.println("");

} }}

class Demonstration {

public static void main(String args[])

MyStack s1 = new MyStack();

s1.display();

s1.push(10);

s1.push(13);

s1.push(16);

s1.display();

System.out.println("pop(): "+s1.pop());

System.out.println("pop(): "+s1.pop());

s1.display();

}}

49 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 33

Ques 33) Write a program to implement nesting of interface.


interface Vehicle {

void drive();

interface Engine {

void start();

void stop(); }}

class Car implements Vehicle, Vehicle.Engine {

public void drive() {

System.out.println("Car is being driven"); }

public void start() {

System.out.println("Car engine started"); }

public void stop() {

System.out.println("Car engine stopped");}}

class Demonstration

{ public static void main(String args[])

{ System.out.println("Deepanshi Mendiratta 05413702022\


n********************************");

Car car = new Car();

car.start();

car.drive();

car.stop();

}}

50 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 34

Ques 34) Write a program that throws user defined exceptions if age of
voter is less than 18.
class AgeException extends Exception

AgeException(){

System.out.println("Error: Age is invalid");

}}

class ElectionCommission

private String name;

private int age;

ElectionCommission(){

name = "no name";

age = 18;

ElectionCommission(String name, int age)

try{

if(age<18)

throw(new AgeException());

this.name = name;

this.age = age;

catch(AgeException e)

System.out.println("Age must be more than 18 for a voter to vote");

51 | P a g e
05413702022 Deepanshi Mendiratta

}}

Void display()

System.out.println("Voter: "+name);

System.out.println("Age: "+age);

}}

class J34

public static void main(String args[])

System.out.println("Deepanshi Mendiratta 05413702022");

ElectionCommission v1 = new ElectionCommission("Ansh Gupta", 18);

v1.display();

ElectionCommission v2 = new ElectionCommission("Krish", 15);

v2.display();

}}

52 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 35

Ques 35) Write a program that throws user defined exceptions if stack is
full or is empty.
class StackOverflowException extends Exception {

StackOverflowException(String message) {

super(message); }}

class StackUnderflowException extends Exception {

StackUnderflowException(String message) {

super(message);}}

class Stack {

int stack[];

int top;

Stack() { stack = new int[5];

top = -1; }

void push(int item) {

try { if (top >= stack.length - 1) {

throw new StackOverflowException("Error: Stack Overflow\n");

} else {

stack[++top] = item;

display(); }

} catch (StackOverflowException e) {

System.out.println(e.getMessage());} }

void pop() { try { if (top < 0) {

throw new StackUnderflowException("Error: Stack Underflow\n");

} else {

top--;

display();

53 | P a g e
05413702022 Deepanshi Mendiratta

} catch (StackUnderflowException e) {

System.out.println(e.getMessage());}}

void display() { if (top == -1) {

System.out.println("Stack is empty");

return; } for (int i = 0; i <= top; i++) {

System.out.print(stack[i] + " | ");}

System.out.println(""); }}

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

System.out.println("Deepanshi Mendiratta 05413702022\


n********************************");

Stack s1 = new Stack();

s1.display(); s1.push(10);

s1.push(20); s1.push(30);

s1.push(40); s1.push(50);

s1.push(60); s1.display();

s1.pop(); s1.pop(); s1.pop();

s1.pop(); s1.pop(); s1.pop();}}

54 | P a g e
05413702022 Deepanshi Mendiratta

PRACTICAL NO – 36

Ques 36) Write a program declaring a java class called SavingsAccount


with members “accountNumber” and “Balance”. Provide member
functions as “depositAmount()” and “withdrawAmount()”. If user tries to
withdraw an amount greater than their balance then throw a user-defined
exception, if bank balance drops below 1000 due to any transaction.
import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

class BalanceTooLowException extends Exception {

public BalanceTooLowException(String message) {

super(message);

}}

class InsufficientFundsException extends Exception {

public InsufficientFundsException(String message) {

super(message);

}}

class SavingsAccount {

private String accountNumber;

private double balance;

public SavingsAccount(String accountNumber, double initialBalance) {

this.accountNumber = accountNumber;

this.balance = initialBalance;

}public void depositAmount(double amount) {

balance += amount;

System.out.println("Deposited: Rs." + amount);}

public void withdrawAmount(double amount) throws InsufficientFundsException,


BalanceTooLowException {

55 | P a g e
05413702022 Deepanshi Mendiratta

if (amount > balance) {

throw new InsufficientFundsException("Insufficient funds. Cannot withdraw Rs." +


amount);

} if (balance - amount < 1000) {

throw new BalanceTooLowException(

"Withdrawal cannot be processed. Minimum balance of Rs.1000 must be


maintained.");

}balance -= amount;

System.out.println("Withdrawn: Rs." + amount);

}public double getBalance() {

return balance;

}}

public class Main {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

SavingsAccount account = null;

System.out.println("Name: Aditya Raj");

try {

System.out.print("Enter account number: ");

String accountNumber = reader.readLine();

System.out.print("Enter initial balance: ");

double initialBalance = Double.parseDouble(reader.readLine());

account = new SavingsAccount(accountNumber, initialBalance);

System.out.print("Enter amount to deposit: ");

double depositAmount = Double.parseDouble(reader.readLine());

account.depositAmount(depositAmount);

System.out.print("Enter amount to withdraw: ");

56 | P a g e
05413702022 Deepanshi Mendiratta

double withdrawAmount = Double.parseDouble(reader.readLine());

account.withdrawAmount(withdrawAmount);

} catch (IOException e) {

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

} catch (NumberFormatException e) {

System.out.println("Invalid input format: " + e.getMessage());

}catch (InsufficientFundsException | BalanceTooLowException e) {

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

} finally {

try {

if (reader != null) {

reader.close();

} } catch (IOException e) {

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

}}

if (account != null) {

System.out.println("Current balance: Rs." + account.getBalance());

} }}

PRACTICAL NO – 37

57 | P a g e
05413702022 Deepanshi Mendiratta

Ques 37) Write relevant programs to show the concept of creating Thread
through thread class and Runnable interface. WAP to print multiples of
2,3,4 simultaneously.

58 | P a g e

You might also like