0% found this document useful (0 votes)
40 views92 pages

Java Practical File Submitted by Poorva Bhardwaj (02390202019)

The document contains a list of 40 programming questions with their corresponding date and topic. The questions cover topics like displaying messages, taking command line arguments, using scanner class, checking even/odd numbers, generating grades, arrays, classes, inheritance, exceptions, files, applets, databases and more. The questions provide output examples and coding snippets to solve each problem.

Uploaded by

poorvabha0704
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)
40 views92 pages

Java Practical File Submitted by Poorva Bhardwaj (02390202019)

The document contains a list of 40 programming questions with their corresponding date and topic. The questions cover topics like displaying messages, taking command line arguments, using scanner class, checking even/odd numbers, generating grades, arrays, classes, inheritance, exceptions, files, applets, databases and more. The questions provide output examples and coding snippets to solve each problem.

Uploaded by

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

INDEX

SNO. DATE TOPIC SIGN


1 12/03/21 Write a program to display a WELCOME message to the
user in the command prompt.
2 12/03/21 Write a program to take COMMAND LINE ARGUMENTS
from the user .Display the No. of Arguments and their
content.
3 12/03/21 Write a program to display name, age and designation of the
user using SCANNER CLASS.
4 12/03/21 Write a program to check whether a number is a number is
POSITIVE ODD, POSITIVE EVEN, NEGATIVE ODD and
NEGATIVE EVEN.
5 12/03/21 Write a program to generate Grades of Students Using IF
ELSE LADDER
6 13/03/21 Write a Program to Print Sum of Cubes of Numbers whose
Range is entered by User.
7 13/03/21 Write a program to generate the following pattern.
8 13/03/21 Write a program USING DO-WHILE LOOP to generate the
FIBONACCI SERIES for first n number
9 14/03/21 Write a program to print the sum of digits of number entered
by user
10 14/03/21 Write a program to print the BINARY EQUIVALENT OF A
DECIMAL NUMBER entered by user
11 15/03/21 Write a program to enter 10 elements in a LINEAR ARRAY
and print the SUM OF ALL THE ELEMENTS
12 15/03/21 Write a program to enter 10 elements in an array and print
SUM OF ODD AND AVERAGE OF EVEN NUMBER.
13 16/03/21 Write a program to SORT the elements in an array using
INSERTION SORT.
14 16/03/21 Write a program to search an element in an array using
LINEAR SEARCH.
15 17/03/21 Create a 2-D ARRAY OF 3X3 and print the SUM OF
LEFT AND RIGHT DIAGONAL ELEMENTS
16 18/03/21 Create a 2-D ARRAY OF 3X3 and print the SUM OF
BORDERED AND UNBORDERED ELEMENTS.
17 18/03/21 Write a program to show usage of all the STRING CLASS
METHODS

1
18 22/05/21 Create a Class called DIMENSION which declares 3
Variables LENGTH, WIDTH and HEIGHT of Type
FLOAT. It contains 2 Constructor first a Default
Constructor
that WELCOMES THE USER to the program and second
1Parameterized Constructor to set the values of the 3
Parameters. Create 2 Overloaded Methods to Calculate the
VOLUME. First Method is Non - Parameterized and
Second is Parameterized
19 22/05/21 Create a Class STUDENT with Attributes ID, NAME, and
AGE. It contains a Method of GETVALUES with all 3
Parameters as ID, NAME, and AGE Use the
KEYWORD THIS to set the values. Create a Method
DISPLAY to display the values.
20 22/05/21 Write a program to show the usage of STATIC KEYWORD
with a Variable and Method.
21 Write a program to create a class AREA and Calculate Area
22/05/21 RECTANGLE and CIRCLE as Subclasses using DYNAMIC
METHOD DISPATCH (METHOD OVERRIDIING).
22 22/05/21 Write a program to create a Class BOX with INSTANCE
Variables WIDTH and HEIGHT. Create another Class
BOXWEIGHT which inherits Class BOX with an additional
INSTANCE Variable WEIGHT. Compute the Volume of
BOX Using NHERITANCE.
23 22/05/21 Write a program to create a Class BOX with INSTANCE
Variables WIDTH and HEIGHT. Create another Class
BOXWEIGHT which inherits Class BOX with an additional
INSTANCE Variable WEIGHT. Compute the Volume of
BOX Using SUPER KEYWORD
24 23/05/21 Write a program to show the Usage of SUPER KEYWORD
with a Variable and Constructor
25 23/05/21 Write a Relevant program to show the Usage of FINAL
KEYWORD with CLASS, VARIABLE and METHOD
26 23/05/21 Create an ABSTRACT CLASS FIGURE and it 2 CLASSES
RECTANGLE and TRIANGLE. Calculate its AREA
Using DYNAMIC METHOD DISPATCH.
27 23/05/21 Write a program to implement STACKS using INTERFACE
28 14/06/21 Create a PACKAGE CIRCLE with a Class to Calculate the
1 Area of the Circle. Import the PACKAGE in another Class
and implement the Calculation f Area

2
29 14/06/21 Write a Relevant program to show the Usage of TRY,
CATCH, THROW and FINALLY
30 14/06/21 Write a program to create USER-DEFINE EXCEPTION
Class and Throw it Using Extends Keyword
31 14/06/21 Write a program to create a File and Check whether the file
earlier exist or not also print the LENGHT of the file
32 14/06/21 Write a program to Read the Content of a File Using
FileInputStream.
33 14/06/21 Write a program to write some user input data in a File
Using FileWriter Class
34 14/06/21 Write a program to Copy the Contents of Two File to another
File Using SequenceInputStream
35 15/06/21 Write a program to Create an APPLET and perform
Addition of two Numbers entered by User. Display the
Output using drawstring().
36 15/06/21 Design an AWT Form for Registration of any Email
Account.
Perform any 2 Event Handling procedures on it.
37 15/06/21 Write a program to Client Server TCP Based Socket
Program to show the requirement and response
Communication.
38 15/06/21 Write a program to Insert Data into an Existing DataBase.
39 15/06/21 Write a program to Select Data into an Existing DataBase
40 15/06/21 Write a program to Insert Data into a table Using
REPARED STATEMENT.

3
Q1 Write a program to display a WELCOME message to the user in
the command prompt.
OUTPUT:-

Coding of Note Pad:-


public class Wel_User
{
public static void main(String arg[])
{
System.out.println("\nWelcome");
}
}

Coding of Command Prompt:-


C:\notepadjavaprogs>javac Wel_User.java
C:\notepadjavaprogs>java Wel_User

4
Q2 Write a program to take COMMAND LINE ARGUMENTS
from the user .Display the No. of Arguments and their content.

OUTPUT:-

Coding of Note Pad:-

5
public class Comdline
{
public static void main(String args[])
{
int count;
count=args.length;
System.out.print(" \n");
System.out.print("The Entered String is:");
for(int i=0;i<count;i++)
{
System.out.print(" "+args[i]);
}
System.out.println("\n Length of array : "+ count);
}
}

Coding of Command Prompt:-

C:\notepadjavaprogs>javac Comdline.java
C:\notepadjavaprogs>javadoc Comdline.java
C:\notepadjavaprogs>java Comdline Hello Mister How Do You Do?

Q3 Write a program to display name, age and designation of the


user using SCANNER CLASS.

OUTPUT:-

6
Coding:-

import java.util.Scanner;
public class UserDetails {
public static void main(String args[])
{
int age;
String name;
String des;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Name: " );
name=sc.nextLine();
System.out.println("Enter Age: " );
age=sc.nextInt();
System.out.println("Enter Designation: " );
des=sc.next();
System.out.println("\n******User Details*******\n");
System.out.println("User name : "+ name );
System.out.println("User Age : "+ age );
System.out.println("User Designation : "+ des );
}
}
7
Q4 Write a program to check whether a number is a number is
POSITIVE ODD, POSITIVE EVEN, NEGATIVE ODD and NEGATIVE
EVEN.

OUTPUT OF EVEN:-

Positive:-
8
Negative:-

OUTPUT OF ODD:-

Positive:-

9
Negative:-

Coding:-
import java.util.Scanner;
public class OddEven
{
public static void main(String args[])

10
{
Scanner sc=new Scanner(System.in);
int n;
System.out.println("Enter Number: ");
n=sc.nextInt();
if(n%2==0)
{
if(n>0)
{
System.out.println("Enterd Number is POSITIVE EVEN NUMBER");
}
else
{
System.out.println("Enterd Number is NEGATIVE EVEN NUMBER");
}
}
else
{
if(n>0)
{
System.out.println("Enterd Nymber is POSITIVE ODD NUMBER");
}
else
{
System.out.println("Enterd Nymber is NEGATIVE ODD NUMBER");
}
}
}
}
Q5 Write a program to generate Grades of Students Using IF ELSE
LADDER

OUTPUT:-

11
Coding:-

import java.util.Scanner;
public class Grade {
public static void main(String args[])
{
int marks;
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Marks: ");
marks=sc.nextInt();
System.out.println("\n*****Grade Of Student*****");
if(marks >=90)
{
System.out.println("Excellent");
System.out.println("Grade = A");
}

else
if( marks >=80 && marks <90 )
{
System.out.println("Very Good");

12
System.out.println("Grade = B");
}
else
if(marks >=70 && marks <80)
{
System.out.println("Good");
System.out.println("Grade = C");
}
else
if(marks >=60 && marks <70)
{
System.out.println("Fair");
System.out.println("Grade = D");
}
else
if(marks >=50 && marks <60)
{
System.out.println("Work Hard");
System.out.println("Grade = E");
}
else
if(marks<=50)
{
System.out.println("Fail");
System.out.println("Grade = F");
}
}
}

Q6 Write a Program to Print Sum of Cubes of Numbers whose


Range is entered by User.

OUTPUT:-

13
Coding:-

import java.util.Scanner;
public class SumofCubs {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,n,m;
long sum=0;
System.out.println("****Enter The Range of sum of cubes*****");
System.out.println("Enter the Starting Range: ");
n=sc.nextInt();
System.out.println("Enter the Ending Range: ");
m=sc.nextInt();

for(i=n;i<=m;i++)
{
sum=sum+i*i*i;
}
System.out.println("Sum of cubes from " + n +" to " + m + "
numbers is: "+ sum);

14
}
}

Q7 Write a program to generate the following pattern.

$ $ $ $ $ $
$ $ $ $ $
$ $ $ $
$ $ $
$ $
$
15
OUTPUT:-

Coding:-

public class Pattern


{
public static void main(String args[])
{
int rows = 6;

for (int i= rows; i>= 1; i--)


{

for (int j=rows; j>i;j--)


{
System.out.print(" ");
}
for (int k=1;k<=i;k++)
{

16
System.out.print("$");
}
System.out.println("");
}
}
}

Q8 Write a program USING DO-WHILE LOOP to generate the


FIBONACCI SERIES for first n number

OUTPUT:-

17
Coding:-
import java.util.Scanner;
public class Fibonacci {
public static void main(String args[])
{
int n,sum;
int num1=0,num2=1,i=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Number: ");
n=sc.nextInt();
System.out.println("****Fibonacci Series of "+ n +" are****");

do
{
System.out.print(num1+" ");
sum=num1+num2;
num1=num2;
num2=sum;
i++;
}
while(i<=n);
}
18
}

Q9 Write a program to print the sum of digits of number entered by


user

OUTPUT:-

19
Coding:-
import java.util.Scanner;
public class SumOfDigits {
public static void main(String args[])
{
long num,n,p;
int sum=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Number or Digits: ");
n=sc.nextLong();
p=n;
while(n>0)
{
num=n%10;
sum+=num;
n=n/10;
}
System.out.println("Sum of Digits of Number "+ p + " is: " + sum );
}
}
Q10 Write a program to print the BINARY EQUIVALENT OF A
DECIMAL NUMBER entered by user.

OUTPUT:-

20
Coding:-

import java.util.Scanner;
public class DecilBinary
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
long bin_num[]=new long[100];
long dec_num;
int i=0;
System.out.println("Enter Decimal Number: " );
dec_num=sc.nextLong();
long num=dec_num;

while (num >0)


{
bin_num[i++]=num%2;
num=num/2;
}
21
System.out.print("Binary Number of decimal number "+ dec_num + " is:
" );
for(int j=i-1;j>=0;j--)
{
System.out.print(bin_num[j]);
}
}
}

Q11 Write a program to enter 10 elements in a LINEAR ARRAY and


print the SUM OF ALL THE ELEMENTS

OUTPUT:-
22
Coding:-

import java.util.Scanner;
public class Array {
public static void main(String args[])
{
int i,n;
int sum=0;
Scanner sc=new Scanner(System.in);
int arr[]=new int[10];
n=arr.length;
System.out.println("Enter The Elements: ");
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.print(" Sum of Array Elements is: ");
for(i=0;i<n;i++)
{

23
sum=sum+arr[i];
}
System.out.println(" "+sum);
}
}

Q12 Write a program to enter 10 elements in an array and print


SUM OF ODD AND AVERAGE OF EVEN NUMBER.

OUTPUT:-

24
Coding:-
import java.util.Scanner;
public class ArrayEvenOdd {
public static void main(String args[])
{
int i;
int sumodd =0,sumeven =0;
int count=0;
double avg=0.0;
Scanner sc=new Scanner(System.in);
int arr[]=new int[10];
System.out.println("Enter the Elements: ");

for(i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
for(i=0;i<arr.length;i++)
{

25
if(arr[i]%2==0)
{
count++;
sumeven+=arr[i];
avg=sumeven/count;
}
else
{
sumodd+=arr[i];
}
}
System.out.println("Sum of ODD Numbers in Array is: " + sumodd );
System.out.println("Average of Even Numbers in Array Is: "+ avg);
}
}

Q13 Write a program to SORT the elements in an array using


INSERTION SORT.

OUTPUT:-

26
Coding:-

import java.util.Scanner;
public class InsertionSortNew {
public static void main(String[] args) {
int arr[] = new int[10];
int i, j = 0, temp;
int size = 10;
Scanner sc = new Scanner(System.in);
System.out.println("Enter element: ");
for (i = 0; i < 10; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Array Before Sort: ");
for (i = 0; i < size; i++)
{
System.out.print(arr[i] + " ");
}

27
System.out.println("\nArray after Sort:");
for (i = 1; i < size; i++)
{
temp = arr[i];
j = i - 1;
while ((temp < arr[j]) && (j >= 0))
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
for (i = 0; i < size; i++)
{
System.out.print(arr[i] + " " );
}
}
}

Q14 Write a program to search an element in an array using LINEAR


SEARCH.

OUTPUT:-
28
Coding:-

import java.util.Scanner;
public class LinearSearch {
public static void main(String args[])
{
int n,item,flag=0;
Scanner sc=new Scanner(System.in);
int arr[];
arr=new int[10];
System.out.println("Enter how many You want to Enter :");
n=sc.nextInt();
System.out.println("Enter the Elements:");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("\n Enter the number to be searched: ");
item=sc.nextInt();
29
for(int i=0;i<n;i++)
{
if(arr[i]==item)
{
flag=1;
System.out.println("Element " + item + " Found at position " + (i+1));
}
}
if(flag==0)
{
System.out.println("Element " + item + " is NOT Found");
}
}
}

Q15 Create a 2-D ARRAY OF 3X3 and print the SUM OF LEFT AND
RIGHT DIAGONAL ELEMENTS.

OUTPUT:-

30
Coding:-

import java.util.Scanner;
public class LeftRightDigonal {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int i,j, n=3,m=3;
int sumleft=0;
int sumright=0;
int arr[][]=new int[n][m];

System.out.println("Enter The Elements: ");


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

31
arr[i][j]=sc.nextInt();
}
}
System.out.println("Left Diagonal Element are: ");
for( i=0;i<n;i++)
{
for( j=0;j<m;j++)
{
if(i==j)
{
System.out.print(" "+arr[i][j]);
sumleft=sumleft+arr[i][j];
}
}
}
System.out.println("\nSum of Left Diagonal Element is: "+sumleft+"\
n");
System.out.println("Right Diagonal Element are: ");
j=m-1;
for(i=0;i<n;i++)
{
System.out.print(" "+arr[i][j]);
sumright=sumright+arr[i][j];
j--;
}
System.out.println("\nSum of Right Diagonal Element is:
"+sumright);
}
}

Q16 Create a 2-D ARRAY OF 3X3 and print the SUM OF BORDERED
AND UNBORDERED ELEMENTS.

OUTPUT:-

32
Coding:-

import java.util.Scanner;
public class Unboadered_BoarderArray {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int row=3,col=3;
int i,j,b = 0;
int sumboundry=0,sumunboundry=0;
int arr[][]=new int[row][col];

System.out.println("Enter the Elements: ");


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

33
}
}
System.out.println("Bordered Elements are:");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(i==0 || i==row-1 || j==0 || j==col-1 )

{
System.out.print( arr[i][j]+" ");
sumboundry=sumboundry+arr[i][j];
}

else
{
b=arr[i][j];
System.out.print(" ");
sumunboundry=sumunboundry+arr[i][j];
}
}
System.out.println();
}
System.out.println("Unbordered Element is:\n "+b);
System.out.println("\nThe sum of Bordered is: " + sumboundry );
System.out.println("The sum of UNBordered is: " + sumunboundry );
}

Q17 Write a program to show usage of all the STRING CLASS


METHODS

OUTPUT:-

34
Coding:-
import java.util.Scanner;
public class StringMethods {
public static void main(String args[])
{
String S1,S2;
35
String S3="Apple";
String S4=" Banana ";
int S5,b=7;
String S6;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the First String: ");
S1=sc.next();
System.out.println("Enter the First String: ");
S2=sc.next();
System.out.println("Third String is:"+S3+"\n"+"Fouth String is:
"+S4+"\n" );

System.out.println("**********String Function************\n" );
System.out.println("Upper Case of First String: "+ S1.toUpperCase() );
System.out.println("Lower Case of Second String: "+ S2.toLowerCase());
System.out.println("Repalce 'o' to 'u' in First String: "+ S1.replace('o', 'u'));
System.out.println("2nd Character At of Second String: "+ S2.charAt(2));

S5=S3.indexOf('p');
System.out.println("Index of 'P' in Third String: "+ S5);
System.out.println("Caparision of First String to Second String: "+
S1.compareTo(S2) );
System.out.println("Trim of Fourth String: "+ S4.trim());
System.out.println("Concationation of Third And Fouth Strings: "+
S3.concat(S4) );
System.out.println("Is First String = Second String: "+ S1.equals(S2) );
System.out.println("Is Third String = Fourth String in any case: "+
S3.equalsIgnoreCase(S4) );
System.out.println("Substring Second String: "+ S2.substring(3) );
System.out.println("Substring Second String: "+ S2.substring(2,5) );
S6=Integer.toString(b);
System.out.println("Convert int to String: "+ S6 );
System.out.println("Index of 'r' in Second String: "+ S2.indexOf("r") );
System.out.println("Index of 'r' and 7th letter in Second String: "+
S2.indexOf("r",7) );

36
}
}

Q18 Create a Class called DIMENSION which declares 3 Variables


LENGTH, WIDTH and HEIGHT of Type FLOAT. It contains 2
Constructor first a Default Constructor that WELCOMES THE
USER to the program and second a Parameterized Constructor to
set the values of the 3 Parameters. Create 2 Overloaded Methods to
Calculate the VOLUME. First Method is Non - Parameterized and
Second is Parameterized
37
OUTPUT:-

Coding:-

class Dimension{
float Length,Width,Height,cal_volume;
Dimension()
{
System.out.println("WELCOME USER-");
}
Dimension(float l,float w,float h)
{
System.out.println("\n***Values in Paramerized Construction****");
Length=l;
Width=w;
Height=h;
}

void volume(float l,float w,float h)


{
38
Length=l;
Width=w;
Height=h;
cal_volume=Length*Width*Height;
System.out.println("\nLength: "+Length+" "+"Width: "+ Width+"
"+"Height: "+" "+ Height);
System.out.println("volume is : "+cal_volume);
}

void volume()
{
System.out.println("Length: "+Length+" "+"Width: "+ Width+"
"+"Height: "+" "+ Height);
cal_volume=Length*Width*Height;
System.out.println("volume is : "+cal_volume);
}
}
public class ConstOverload {
public static void main(String args[])
{
Dimension d1=new Dimension();
Dimension d2=new Dimension(20,30,40);
d2.volume();
d1.volume(90,80,70);
}}
Q19 Create a Class STUDENT with Attributes ID, NAME, and
AGE. It contains a Method of GETVALUES with all 3 Parameters
as ID, NAME, and AGE Use the KEYWORD THIS to set the
values. Create a Method DISPLAY to display the values.

OUTPUT:-

39
Coding:-
class Student1
{
int id,Rno;
String Name;
void getvalue(int id,int Rno,String Name)
{
this.id=id;
this.Rno=Rno;
this.Name=Name;
}

void display()
{
System.out.println("Student Id is: "+ id);
System.out.println("Student Roll Number is: "+ Rno);
System.out.println("Student Name is: "+ Name);
}
40
}

public class VarUsingThis {


public static void main(String args[])
{ System.out.println("***Use of This Keyword for Variable***");
Student1 s1=new Student1();
s1.getvalue(2,23,"Poorva");
s1.display();
}
}

Q20 Write a program to show the usage of STATIC KEYWORD with


a Variable and Method.

OUTPUT:-

41
Coding:-

class Student
{
int age;
static int i;
static String name="poorva";
Student()
{
System.out.println("object is created");
i++;
}

Student(int a)
{
age=a;
System.out.println("parameterized constructor is created");
System.out.println("\n***Static Member ***");
System.out.println( "Name of Student is "+name +" and age is " +age);

42
i++;
}

static void calsq(int n)


{
System.out.println("\n***Static Member function***");
System.out.println("square of number is: "+n*n);
}
}

public class StaticUses {


public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
Student s3=new Student(20);
System.out.println("\n***Total count of constructors is***: "+
Student.i); //static value for whole class

//System.out.println(s1.i); //static value for single object of class


//System.out.println(s2.i);
//System.out.println(s3.i);
Student.calsq(3); // static member function for whole class
}
}

Q21 Write a program to create a class AREA and Calculate Area of


RECTANGLE and CIRCLE as Subclasses using DYNAMIC
METHOD DISPATCH (METHOD OVERRIDIING).

OUTPUT:-

43
Coding:-

class Area{
int length,breath,height;
void set(int l,int b,int h){
length=l;
breath=b;
height=h;
}
void cal_Area(){
System.out.println("*** Area Class ***");
int a=length*breath*height;
System.out.println("Area is: "+a+"\n");
}}
class Rectangle1 extends Area{
void get(int l,int b){
length=l;
breath=b;
}

44
void cal_Area(){
System.out.println("*** Rectangle Class ***");
int a=length*breath;
System.out.println("Area of Rectangle is: "+a+"\n");
}
}

class Circle extends Area{


double pi=3.14;
int radius;
void take(int r){
radius=r*r;
}
void cal_Area(){
System.out.println("*** Circle Class ***");
double a=pi*radius;
System.out.println("Area of circle is: "+a+"\n");

}
}

public class Dynamic_Dispatch {


public static void main(String args[]){
Area ar1=new Area();
Rectangle1 r1=new Rectangle1();
Circle c1=new Circle();
System.out.println("\n*** Dynamic Dispatch Method ***\n");
ar1.set(9, 9, 4);
ar1.cal_Area();
r1.get(10, 10);
r1.cal_Area();
c1.take(2);
c1.cal_Area();
}
}

45
Q22 Write a program to create a Class BOX with INSTANCE
Variables WIDTH and HEIGHT. Create another Class
BOXWEIGHT which inherits Class BOX with an additional
INSTANCE Variable WEIGHT. Compute the Volume of BOX
Using NHERITANCE.

OUTPUT:-

46
Coding:-
import java.util.Scanner;
class Box
{
int height,width;
void setdata(int h,int w)
{
System.out.println("**Method of Box Class**");
height=h;
width=w;
}
void getdata()
{
System.out.println("width is: "+width+" "+"height is: "+height);
}
}

class BoxWeight extends Box


{

47
int weight;
void volume()
{
height=30;
width=30;
System.out.println("width is: "+width+" "+"height is: "+height+" "+
"weigth is: "+weight);
int vol=width*height*weight;
System.out.println("Volume is: "+vol);
}
}

public class Inheritance {


public static void main(String args[])
{
BoxWeight bw1=new BoxWeight();
BoxWeight bw2=new BoxWeight();
Scanner sc=new Scanner(System.in);
bw1.setdata(23,34);
bw1.getdata();
System.out.println("\n**Method of BoxWeight Class**");
System.out.println("Enter Weight: ");
bw2.weight=sc.nextInt();
bw2.volume();
}
}
Q23 Write a program to create a Class BOX with INSTANCE
Variables WIDTH and HEIGHT. Create another Class
BOXWEIGHT which inherits Class BOX with an additional
INSTANCE Variable WEIGHT. Compute the Volume of BOX
Using SUPER KEYWORD

OUTPUT:-

48
Coding:-

class Box1
{
int height,width;
Box1()
{
height=50;
width=30;
}
}

class BoxWeight1 extends Box1


{
int weight=90;
BoxWeight1()
{
super();
System.out.println("Width is: "+width+" "+"Height is: "+height+" "+
"Weigth is: "+weight);
int vol=width*height*weight;
49
System.out.println("Volume is: "+vol);
}
}

public class SuperInheritence {


public static void main(String args[])
{
System.out.println("\n****Use of Super Keyword****\n");
BoxWeight1 bwt1=new BoxWeight1();
}
}

Q24 Write a program to show the Usage of SUPER KEYWORD with


a Variable and Constructor

OUTPUT:-

50
Coding:-

class Flower{
int count=5;
Flower()
{
String FlName="White Roses";
System.out.println(" Make A booke of "+FlName);
}
}

class Garden extends Flower{


Garden()
{
super();
System.out.println( " with " +super.count +" Pink Roses");
51
}
}

public class SuperUse {


public static void main(String args[])
{
System.out.println("\n***Use of super to call a Constructor and a
Variable***\n");
Garden g1=new Garden();
}
}

Q25 Write a Relevant program to show the Usage of FINAL


KEYWORD with CLASS, VARIABLE and METHOD

OUTPUT:-

52
Coding:-
final class FINAL{
FINAL(){
System.out.println("Hi Poorva.I'am Constructor of final class");
}
}

class House{
final int cash;
House(){
cash=200000;
System.out.println("I Bought House of Rupees "+cash);
}
final void Rent(){
System.out.println(" i have taken Rental house");
}}
public class UseOfFinal {
public static void main(String args[])
{
System.out.println("\n*** Constructor of Final Class***");
FINAL f1=new FINAL();
53
System.out.println("\n***Final Variable***");
House h1=new House();
System.out.println("\n***Final Function***");
h1.Rent();
}
}

Q26 Create an ABSTRACT CLASS FIGURE and its 2


SUBCLASSES RECTANGLE and TRIANGLE. Calculate its AREA
Using DYNAMIC METHOD DISPATCH.

OUTPUT:-
54
Coding:-

abstract class Figure{


void me(){
System.out.println("Hi I'm Abtract Class Member Function");
}
abstract void Area();
}

class Rectangle extends Figure{


int Width,Length;
void me()
{
super.me();
System.out.println("Rectangle class called Abtract Class Member");
}
55
void getdata(int w,int l)
{
Width=w;
Length=l;
}
void Area()
{
int ar=Width*Length;
System.out.println("Area of Rectangle: " +ar);
}
}

class Triangle extends Figure{


int Base,Height;
void getdata(int b,int h)
{
Base=b;
Height=h;
}
void Area()
{
int ar=Base*Height;
System.out.println("Area of Triangle: "+ar);
}
}

public class AbstractClass {


public static void main(String args[])
{
Rectangle r1=new Rectangle();
Triangle t1=new Triangle();
System.out.println("\n****Overriding Abstract Member Fuction*****\n");
t1.getdata(2, 3);
t1.Area();

56
r1.getdata(5, 7);
r1.Area();
System.out.println("\n****Calling Abstract class Member Fuction*****\n");
r1.me();
}
}

Q27 Write a program to implement STACKS using INTERFACE.


OUTPUT OF PUCH FUNCTION (CASE 1):-

57
OUTPUT OF PEEP FUNCTION (CASE 2):-

OUTPUT OF POP FUNCTION (CASE 3):-

58
OUTPUT OF DISPLAY FUNCTION (CASE 4):-

Coding:-

59
import java.util.Scanner;
interface Stack
{
public void push();
public void pop();
public void peep();
public void display();
}
class Stackbase implements Stack{
Scanner sc=new Scanner(System.in);
int max_size=5;
int arr[]=new int[5];
int top=-1,i;
int item;
public void push()
{

if(top==(max_size-1))
{
System.out.println("\n***Stack Overflow***");
}
else
{

item=sc.nextInt();
top++;
arr[top]=item;
}
}

public void pop()


{
if(top==-1)
{
60
System.out.println ("\n***Stack UnderFlow***");
}
else
{
item=arr[top];
System.out.println ("\n***The Popped Element is:***\n"+" "+item);
top--;
}
}

public void peep()


{
System.out.println ("\n***The top most Element in stack is:***\n"+"
"+arr[top]);

}
public void display()
{
System.out.println("\n***Elements in the stack are:***");
for(i=top;i>=0;i--)
{
System.out.print(" "+arr[i]+" ");
}
}
}

public class InterfaceUse {


public static void main(String args[]){
Scanner sc=new Scanner(System.in);
Stackbase s1=new Stackbase();
System.out.println("\n***Enter the Element in the Stack:***");
for(int i=1;i<=4;i++)
{
s1.push();
}

61
System.out.println("**Enter the choice to Perform the following
Operation on Stack**");
System.out.println("(1) Push");
System.out.println("(2) Peep");
System.out.println("(3) Pop");
System.out.println("(4) Display");
System.out.println("\nEnter choice: ");
int choice=sc.nextInt();
switch (choice){
case 1:System.out.println("\n***Enter the element in the Stack:***");
s1.push();
s1.display();
break;
case 2:s1.peep();
break;
case 3:s1.pop();
s1.display();
break;
case 4:s1.display();
break;
}

}
}

Q28 Create a PACKAGE CIRCLE with a Class to Calculate the


Area of the Circle. Import the PACKAGE in another Class and
implement the Calculation f Area

OUTPUT:-

62
Coding:-
Creating new Package and a Class in it:-

package Circle_Package;
import java.util.Scanner;
public class Circle {
Scanner sc=new Scanner(System.in);
double pie=3.14;
double Calculate;
public void Cal_Area(){
System.out.println("Enter the value of Radius: ");
int r=sc.nextInt();
Calculate=pie*r*r;
System.out.println("Area of Circle is: "+Calculate);
}
}

Importing package in a class in different package:-

import Circle_Package.Circle;
//import Circle_Package.*;
public class Package {

63
public static void main(String args[]){
Circle c1=new Circle();
// Circle_Package.Circle c1=new Circle_Package.Circle();
System.out.println("***Use User_Defined of Package***\n");
c1.Cal_Area();
}
}

Q29 Write a Relevant program to show the Usage of TRY, CATCH,


THROW and FINALLY.
OUTPUT:-

64
Coding:-

import java.util.Scanner;
public class useoftexcep {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);

try
{
int a,b;
float c;
System.out.println("***Use of try,catch,throw,finally***");
System.out.println("Enter first value: ");
a=sc.nextInt();
System.out.println("Enter Second Value: ");
b=sc.nextInt();

if(b == 0)
{
throw new ArithmeticException();
}

65
else
{
c=a/b;
System.out.println("Result of first number dividing second is:"+c);
}
}

catch(ArithmeticException ex)
{
System.out.println("Division by zero is not possible");
}

finally
{
System.out.println("Hi am Final Block");
}
}
}

Q30 Write a program to create USER-DEFINE EXCEPTION


Class and Throw it Using Extends Keyword.

OUTPUT:-

66
Coding:-

import java.lang.Exception;
import java.util.Scanner;
class myexception extends Exception{
myexception(String message)
{
super(message);
}
}

public class userdefinedthrow {


public static void main(String args[]){
Scanner sc=new Scanner(System.in);
try
{
int a,b;

67
float c;
System.out.println("***User Defined Exception extends Throw
Keyword***");
System.out.println("Enter first value: ");
a=sc.nextInt();
System.out.println("Enter Second Value: ");
b=sc.nextInt();

if(b == 0)
{
throw new myexception("Division by zero is not possible");
}
else
{
c=a/b;
System.out.println("Result of first number dividing second is:"+c);
}
}

catch(myexception ex)
{
System.out.println(ex);
}

finally{
System.out.println("Hi am Finally Block");
}}}

Q31 Write a program to create a File and Check whether the file
earlier exist or not also print the LENGHT of the file.

OUTPUT:-

68
OUTPUT OF FILE1 (Content After creation of file):-

Coding:-

import java.io.*;
public class File_Existence {
public static void main(String args[]) throws IOException
69
{
File f1=new File("File1");

if(f1.createNewFile())
{
System.out.println("New File created"+ f1.getName());
}
else
{
System.out.println("File1 is Already Exists");
}

System.out.println("***Checking Whether File Exists***");


if(f1.exists())
{
System.out.println("File1 Exists");
System.out.println("\n***Calculating Length of Existing File***");
System.out.println("Length of File1 is:"+f1.length());
}

else
{
System.out.println("File1 Don't Exists");
}
}
}

Q32 Write a program to Read the Content of a File Using


FileInputStream.

FILE1 Content:

70
OUTPUT

Coding:-

import java.io.*;
public class ReadContentOfFile {
public static void main(String args[])throws IOException{
File f1=new File("File1");

71
FileInputStream fin=new FileInputStream("File1");

System.out.println("**Readig Content of a File Using


FileInputeStream**");

int i;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
}

Q33 Write a program to write some user input data in a File Using
FileWriter Class

OUTPUT

72
OUTPUT OF FILE1 (Content written by using FileWriter)

Coding:-

import java.io.*;
import java.util.Scanner;
public class WriteUserDataInFile {

73
public static void main(String args[])throws IOException{
Scanner sc=new Scanner(System.in);
FileWriter fout=new FileWriter("File1");

System.out.println("\n***Using FileWiter Write content in File***\n");


System.out.println("Enter the String You Want to Write in File:");
String s1=sc.nextLine();

System.out.println("\nWritten in File ");


fout.write(s1);
fout.close();

}
}

Q34 Write a program to Copy the Contents of Two File to another


File Using SequenceInputStream.

FILE3 Content

74
FILE4 Content

OUTPUT

75
OUTPUT OF FILE5 (Content written by using SequenceInputStream)

Coding:-

76
import java.io.*;
public class SequencingInFile {
public static void main(String args[])throws IOException{
File f3=new File("File3");
File f4=new File("File4");
File f5=new File("File5");

FileInputStream fin =new FileInputStream("File3");


FileInputStream fin1=new FileInputStream("File4");
FileOutputStream fout=new FileOutputStream("File5");

System.out.println ("\n****Checking whether File Exists Or Not***\n");


if(f3.createNewFile())
{
System.out.println("New File created"+ f3.getName());
}
else
{
System.out.println("Already Exists");
}

if(f4.createNewFile())
{
System.out.println("New File created"+ f4.getName());
}
else
{
System.out.println("Already Exists");
}

if(f5.createNewFile())
{

77
System.out.println("New File created"+ f5.getName());
}
else
{
System.out.println("Already Exists");
}

System.out.println("\n***Copying Content from Two File to Another***");


SequenceInputStream seq =new SequenceInputStream(fin, fin1);

int j;
while((j=seq.read())!=-1){
System.out.print((char)j);
fout.write((char)j);
}
seq.close();
fin.close();
fin1.close();
}
}

Q35 Write a program to Create an APPLET and perform Addition


of two Numbers entered by User. Display the Output using
drawstring().
78
OUTPUT:-

Coding:-

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

public class Addition extends Applet {


TextField t1,t2;
int Result;

public void init() {


Label l1=new Label("*ADDITION OF TWO NUMBER* ");
add(l1);
Label l2=new Label("Enter First Number: ");
add(l2);
t1=new TextField(10);
add(t1);
Label l3=new Label("Enter second Number: ");
add(l3);
79
t2=new TextField(10);
add(t2);
t1.setText("0");
t2.setText("0");
}
public void paint(Graphics g){

try{
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
}
catch(Exception e){}
Result=a+b;
String rs;
rs=String.valueOf(Result);
g.drawString("Sum of two Numbers is:", 100, 150);
g.drawString(rs,150,168);
}
public Boolean Action(Event event,Object object){
repaint();
return true;
}
}

Q36 Design an AWT Form for Registration of any Email


Account. Perform any 2 Event Handling procedures on it.

OUTPUT OF BUTTON EVENT:-


80
OUTPUT OF KEYTYPED EVENT:-

81
Coding:-

public class Emial_Registeration extends java.awt.Frame {

public Emial_Registeration() {
initComponents();
}

private void exitForm(java.awt.event.WindowEvent evt) {


System.exit(0);
}
Coding for ActionPerformed Event:-

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {


textField6.setText("Registered SuccessFully");
82
}

Coding for keyType Event:-

private void textField4KeyTyped(java.awt.event.KeyEvent evt) {


String s1=textField4.getText();
textField5.setText(" "+s1);// TODO add your handling code here:
}

public static void main(String args[]) {


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Emial_Registeration().setVisible(true);
}
});
}

Q37 Write a program to Client Server TCP Based Socket Program


to show the requirement and response Communication.

SERVER OUTPUT:-

83
CLIENT OUTPUT

 Server coding:

import java.io.*;
import java.net.*;

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

try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
dout.writeUTF("Hello Client i am your Server and Your Request is Accepted");
ss.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

 Client coding:

import java.io.*;
import java.net.*;
public class Client1 {

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

try{
Socket s=new Socket("localhost",6666);
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server i am your new Client");
String str=(String)dis.readUTF();
System.out.println("message= "+str);
dout.flush();
dout.close();
s.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

Q38 Write a program to Insert Data into an Existing DataBase.

OUTPUT

86
Coding:

import java.sql.*;
public class DataBase {
public static void main(String args[]){

try{
//step1 load the driver class
Class.forName("org.apache.derby.jdbc.ClientDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:derby://localhost:1527/Poorva_Bhardwaj","PoorvaBha","Akidel@123");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


int result=stmt.executeUpdate("insert into student values(3,'Sneha Dhar')");
System.out.println(result+"row effected");

//step5 close the connection object


con.close();

87
}
catch(Exception e){
System.out.println(e);
}
}
}

Q39 Write a program to Select Data into an Existing DataBase.

OUTPUT

88
Coding:

import java.sql.*;
public class DataBase {
public static void main(String args[]){

try{
//step1 load the driver class
Class.forName("org.apache.derby.jdbc.ClientDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:derby://localhost:1527/Poorva_Bhardwaj","PoorvaBha","Akidel@123");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from Student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2));

//step5 close the connection object


con.close();
}
catch(Exception e){
89
System.out.println(e);
}
}
}

Q40 Write a program to Insert Data into a table Using


PREPARED STATEMENT.

OUTPUT

90
Coding:-

import java.sql.*;
import java.util.*;
public class DataBase {
public static void main(String args[]){

try{
//step1 load the driver class
Class.forName("org.apache.derby.jdbc.ClientDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:derby://localhost:1527/Poorva_Bhardwaj","PoorvaBha","Akidel@123");
System.out.println("*Insertion by using Prepared Statement*\n");

//step4 execute query


PreparedStatement stmt=con.prepareStatement("insert into student
values(?,?)");
Scanner sc=new Scanner(System.in);
System.out.println("Enter Roll Number: ");
int a=sc.nextInt();
System.out.println("Enter Name: ");
String b=sc.next();

91
stmt.setInt(1, a);
stmt.setString(2, b);

int i=stmt.executeUpdate();
System.out.println(i+"Record Inserted");

//step5 close the connection


con.close();
}
catch(Exception e){ System.out.println(e);}
}
}

92

You might also like