0% found this document useful (0 votes)
36 views90 pages

JAVA Lab - Manual

java lab manual

Uploaded by

idunnoblind
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)
36 views90 pages

JAVA Lab - Manual

java lab manual

Uploaded by

idunnoblind
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/ 90

GOVERNMENT POLYTECHNIC

PORBANDAR

affiliated to

Gujarat Technological University, Ahmedabad

Laboratory Manual

JAVA PROGRAMMING
(3350704)
D. E. Third Year (Semester– V)

Government Polytechnic - Porbandar


Opp. Airport, National Highway
Porbandar – 360578
GOVERNMENT POLYTECHNIC
PORBANDAR

Enrollment No: 196270307024

Name: Joshi Viren Chandrakant

Address: Bokhira,Porbandar

Subject: JAVA

Branch: Computer

Term: 07/06/2021 to 30/09/2021


GOVERNMENT POLYTECHNIC
PORBANDAR

Computer Engineering Department

Certificate

This is to certify that


Mr./Ms Joshi Viren Chandrakant Enrollment No: 196270307024
Of 5th Semester Diploma course in Computer Engineering has
satisfactorily completed his/her term work in Java Programming
(3350704) from 07/06/2021 to 30/09/2021 in Government
Polytechnic, Porbandar.

Date of Submission: _06/10/2021_____________________

Staff in charge Head of Department

______________________ ___________________
GOVERNMENT POLYTECHNIC
PORBANDAR

VISION OF THE INSTITUTE


To emerge as a leading polytechnic having value based effective technical
education system in the region to meet the future demand of industry and
society.

MISSION OF THE INSTITUTE


M1: To impart adequate technical skill and capability to accept challenges and
to adopt rapidly changing scenario in technological development as well as to
take up higher studies.

M2: Foster close networking with the industry, alumni and the guardians.

M3: Promote professional ethics and human values, integrity, accountability


and transparency.

M4: Promote entrepreneurship practices to generate employment opportunities.

M5: Create conductive academic environment.


GOVERNMENT POLYTECHNIC
PORBANDAR

COMPUTER ENGINEERING
DEPARTMENT

VISION OF THE DEPARTMENT


To achieve excellence in Computer Engineering by imparting technical and
problem-solving skills along with ethical value to meet industrial requirements
having social and environmental concerns.

MISSION OF THE DEPARTMENT


M1: To provides a learning ambiance to enhance discipline knowledge,
technical skill and problem solving skill.

M2: To motivates students for lifelong learning to adapt challenges in rapidly


changing technology.

M3: To induces ethical values and spirit of social commitment.

M4: To provide opportunities to promote leadership skill required in Computer


Engineering industry’s diverse culture.
Subject: Java Programming
Subject Code: C304, 3350704

Course Outcomes:
CO1: Understand the use of OOPs concepts.

CO2: Apply basic building blocks of Java Programming Language and OOP
concepts in program.

CO3: Analyse the role of Packages, Interfaces and inheritance in program


design using JAVA.

CO4: Develop program using multithreading and exception handling.

CO5: Develop an object oriented program to handling data file.


Subject: Java Programming
Subject Code: C304, 3350704

Hardware Requirements:
 Computer system with Intel i3 (or equivalent) processor and at least 2
GB of RAM.

Software Requirements:
 JDK 1.2 or higher.
List of Practicals
Sr. Mapping Mapping with
Practical Title
No. with COs POs, PSOs

Install JDK, write a simple “Hello World” or similar java program,


1 compilation, debugging, executing using java compiler and CO2 PO1,PSO2
interpreter.

2 Write a program in Java to generate first n prime numbers. CO2 PO1,PSO2

Write a program in Java to find maximum of three numbers using


3 CO2 PO1,PSO2
conditional operator

Write a program in Java to find second maximum of n numbers


4 CO2 PO1,PSO2
without using arrays

Write a program in Java to reverse the digits of a number using


5 CO2 PO1,PSO2
while loop

6 Write a program in Java to convert number into words & print it CO2 PO1,PSO2

Write programs in Java to use Wrapper class of each primitive


7 CO2 PO1,PSO2
data types

8 Write a program in Java to multiply two matrix CO2 PO1,PSO2

Write a static block which will be executed before main( ) method


9 CO2 PO1,PSO2
in a class.

Write a program in Java to demonstrate use of this keyword.


10 Check whether this can access the private members of the class or CO2 PO1,PSO2
not.

Write a program in Java to develop overloaded constructor. Also


11 develop the copy constructor to create a new object with the state CO3 PO1,PSO2
of the existing object.

Write a program in Java to demonstrate the use of private


12 constructor and also write a method which will count the number CO3 PO1,PSO2
of instances created using default constructor on

Write a program in Java to demonstrate the use of 'final' keyword


13 CO3 PO1,PSO2
in the field declaration. How it is accessed using the objects.

Develop minimum 4 program based on variation in methods i.e.


14 passing by value, passing by reference, returning values and CO3 PO1,PSO2
returning objects from methods.

Write a program in Java to demonstrate single inheritance,


15 CO3 PO1,PSO2
multilevel inheritance and hierarchical inheritance.
Create a class to find out whether the given year is leap year or
16 CO3 PO1,PSO2
not. (Use inheritance for this program)

Write an application that illustrates how to access a hidden


variable. Class A declares a static variable x. The class B extends
17 CO3 PO1,PSO2
A and declares an instance variable x. display( ) method in B
displays both of these variables.

Write a program in Java in which a subclass constructor invokes


18 CO3 PO1,PSO2
the constructor of the super class and instantiate the values.

Write a program that illustrates interface inheritance. Interface P12


inherits from both P1 and P2. Each interface declares one constant
19 and one method. The class Q implements P12. Instantiate Q and CO3 PO1,PSO2
invoke each of its methods. Each method displays one of the
constants.

Write an application that illustrates method overriding in the same


20 package and different packages. Also demonstrate accessibility CO3 PO1,PSO2
rules in inside and outside packages.

Describe abstract class called Shape which has three subclasses


say Triangle, Rectangle, Circle. Define one method area()in the
21 abstract class and override this area() in these three subclasses to CO3 PO1,PSO2
calculate for specific object i.e. area() of Triangle subclass should
calculate area of triangle etc. Same for Rectangle and Circle

Write a program in Java to demonstrate implementation of


22 CO3 PO1,PSO2
multiple inheritance using interfaces.

23 Write a program in Java to demonstrate use of final class. CO3 PO1,PSO2

Write a program in Java to develop user defined exception for PO1, PO3, PO4,
24 CO4
'Divide by Zero' error. PSO2

Write a program in Java to demonstrate multiple try block and PO1, PO3, PO4,
25 CO4
multiple catch exception PSO2

Write an small application in Java to develop Banking Application


in which user deposits the amount Rs 1000.00 and then start PO1, PO3, PO4,
26 CO4
withdrawing of Rs 400.00, Rs 300.00 and it throws exception "Not PSO2
Sufficient Fund" when user withdraws Rs. 500 thereafter.

Write a program that executes two threads. One thread displays


“Thread1” every 2,000 milliseconds, and the other displays PO1, PO3, PO4,
27 CO4
“Thread2” every 4,000 milliseconds. Create the threads by PSO2
extending the Thread class
Write a program that executes two threads. One thread will print
PO1, PO3, PO4,
28 the even numbers and the another thread will print odd numbers CO4
PSO2
from 1 to 50.

Write a program in Java to demonstrate use of synchronization of


PO1, PO3, PO4,
29 threads when multiple threads are trying to update common CO4
PSO2
variable.

Write a program in Java to create, write, modify, read operations


30 CO5 PO1, PO3, PO4
on a Text file.
Lab Evaluation Rubrics:
Lab Performance (LP) Rubrics
Criteria Excellent (4) Good (3) Substandard (2) Poor (1)

Lab * Student * Student needs * Student performs * Student cannot


Performance Performs some help from of the experiments complete
(LP) experiment as per faculty to with the help from experiment.
the instructions perform the faculty. * Student has not
given without experiments as * Student has no understanding of lab
any help from per the clear understanding objectives and
faculty. instruction of lab objectives concepts.
* Student * Student has and concepts. * Student cannot
demonstrates an sufficient * Student cannot explain concepts to
accurate understanding of explain concepts to fellow classmates.
understanding of lab objectives and fellow classmates.
the lab objectives concepts.
and concepts. * Student can
* Student can understand
explain concepts concepts by
to fellow himself but
classmates. cannot explain it
to fellow
classmates.

Lab Assignment (LA) Rubrics


Criteria Excellent (4) Good (3) Substandard (2) Poor (1)

Lab * Student * Student has a * Student has * Student turns in


Assignment demonstrates an basic knowledge problems with both lab report late or
accurate of content, but the graphs and the the report is so
understanding of may lack some answers. incomplete and/or
the lab objectives understanding of * Student appears to so inaccurate.
and concepts. some concepts. have not fully
* Student answers * Student grasped the lab * Programs are not
questions answers content and the complete.
completely and questions fairly Programs possess
correctly. well. some errors.
* Programs are
written neatly, * Programs
has no error. could have be
written more
neatly.

* Programs has
no errors or
errors are
minimal
INDEX
Staff PA
Sr. Page
Practical Date Signatur LA
No No LP
e
Install JDK, write a simple “Hello World” or similar java
1 program, compilation, debugging, executing using java 08/06/2021
compiler and interpreter.
2 Write a program in Java to generate first n prime numbers. 10/06/2021
Write a program in Java to find maximum of three
3 10/06/2021
numbers using conditional operator
Write a program in Java to find second maximum of n
4 15/06/2021
numbers without using arrays
Write a program in Java to reverse the digits of a number
5 17/06/2021
using while loop
Write a program in Java to convert number into words &
6 22/06/2021
print it
Write programs in Java to use Wrapper class of each
7 01/07/2021
primitive data types
8 Write a program in Java to multiply two matrix 06/07/2021
Write a static block which will be executed before main( )
9 06/07/2021
method in a class.
Write a program in Java to demonstrate use of this
10 keyword. Check whether this can access the private 15/07/2021
members of the class or not.
Write a program in Java to develop overloaded constructor.
11 Also develop the copy constructor to create a new object 20/07/2021
with the state of the existing object.
Write a program in Java to demonstrate the use of private
12 constructor and also write a method which will count the 22/07/2021
number of instances created using default constructor only.
Write a program in Java to demonstrate the use of 'final'
13 keyword in the field declaration. How it is accessed using 27/07/2021
the objects.
Develop minimum 4 program based on variation in
14 methods i.e. passing by value, passing by reference, 29/07/2021
returning values and returning objects from methods.
Write a program in Java to demonstrate single inheritance, 03/08/2021
15
multilevel inheritance and hierarchical inheritance.
Create a class to find out whether the given year is leap 05/08/2021
16
year or not. (Use inheritance for this program)
Write an application that illustrates how to access a hidden
variable. Class A declares a static variable x. The class B 10/08/2021
17
extends A and declares an instance variable x. display( )
method in B displays both of these variables.
18 Write a program in Java in which a subclass constructor 12/08/2021
invokes the constructor of the super class and instantiate
the values.
Write a program that illustrates interface inheritance.
Interface P12 inherits from both P1 and P2. Each interface
19 declares one constant and one method. The class Q 02/09/2021
implements P12. Instantiate Q and invoke each of its
methods. Each method displays one of the constants.
Write an application that illustrates method overriding in
20 the same package and different packages. Also demonstrate 07/09/2021
accessibility rules in inside and outside packages.
Describe abstract class called Shape which has three
subclasses say Triangle, Rectangle, Circle. Define one
method area()in the abstract class and override this area() 09/09/2021
21
in these three subclasses to calculate for specific object i.e.
area() of Triangle subclass should calculate area of triangle
etc. Same for Rectangle and Circle
Write a program in Java to demonstrate implementation of 14/09/2021
22
multiple inheritance using interfaces.
23 Write a program in Java to demonstrate use of final class. 14/09/2021
Write a program in Java to develop user defined exception 16/09/2021
24
for 'Divide by Zero' error.
Write a program in Java to demonstrate multiple try block 18/09/2021
25
and multiple catch exception
Write an small application in Java to develop Banking
Application in which user deposits the amount Rs 1000.00
26 and then start withdrawing of Rs 400.00, Rs 300.00 and it 21/09/2021
throws exception "Not Sufficient Fund" when user
withdraws Rs. 500 thereafter.
Write a program that executes two threads. One thread
displays “Thread1” every 2,000 milliseconds, and the other 23/09/2021
27
displays “Thread2” every 4,000 milliseconds. Create the
threads by extending the Thread class
Write a program that executes two threads. One thread will
28 print the even numbers and the another thread will print 24/09/2021
odd numbers from 1 to 50.
Write a program in Java to demonstrate use of
29 synchronization of threads when multiple threads are trying 28/09/2021
to update common variable.
Write a program in Java to create, write, modify, read 30/09/2021
30
operations on a Text file.
Page: JAVA (3350704)

Practical - 1

AIM:
Install JDK, write a simple “Hello World” or similar java program, compilation,
debugging, executing using java compiler and interpreter.

PROGRAM: /

Step 1: Go to link. Click on Download JDK. For java latest version.

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 2: Next,

1. Accept License Agreement

Download latest Java JDK for your version(32 or 64 bit) of java for
Windows.
Download latest Java JDK for your version(32 or 64 bit) of java for
Windows.

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 3: Once the download is complete, run the exe for install JDK. Click
Next

Step 4: Once the installation is complete click Close

Government Polytechnic, Porbandar


Page: JAVA (3350704)

How to set Environment Variables in Java: Path and


Classpath

The PATH variable gives the location of executables like javac, java etc. It
is possible to run a program without specifying the PATH but you will
need to give full path of executable like C:\Program Files\Java\
jdk1.8.0_131\bin\javac A.java instead of simple javac A.java
The CLASSPATH variable gives the location of the Library Files.
Let's look into the steps to set the PATH and CLASSPATH
Step 1: Right Click on the My Computer and Select the properties

Step 2: Click on advanced system settings

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 3: Click on Environment Variables

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 4: Click on new Button of User variables

Step 5: Type PATH in the Variable name.

Step 6: Copy the path of bin folder which is installed in JDK folder.

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 7: Paste Path of bin folder in Variable value and click on OK Button.

Note: In case you already have a PATH variable created in your PC, then
paste your path separated with a semi-comma (;), edit the PATH variable
to

PATH = <JDK installation directory>\bin;%PATH%;

Here, %PATH% appends the existing path variable to our new value

Step 8: You can follow a similar process to set CLASSPATH.

Note: In case you java installation does not work after installation, change
classpath to

CLASSPATH = <JDK installation directory>\lib\tools.jar;

Step 9: Click on OK button

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Step 10) Go to command prompt and type javac commands.


If you see a screen like below, Java is installed.

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

PROGRAM:
public class Practical1

public static void main(String[] args)

System.out.printf("HEllo Word ");

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 2

AIM:
Write a program in Java to generate first n prime numbers.

PROGRAM:
public class Practical2

public static void main(String[] args)

int ct=0,n=0,i=1,j=1;

while(n<10)

j=1;

ct=0;

while(j<=i)

if(i%j==0)

ct++;

j++;
}

if(ct==2)

System.out.printf("%d ",i);

n++;

i++;

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 3

AIM:
Write a program in Java to find maximum of three numbers using conditional
operator.

PROGRAM:
mport java.util.Scanner;
i

public class Practical3

public static void main(String[] args)

int a, b, c;

Scanner s = new Scanner(System.in);

System.out.print("Enter A :-");

a = s.nextInt();

System.out.print("Enter B :-");

b = s.nextInt();

System.out.print("Enter C :-");
c = s.nextInt();

if(a > b && a>c ){

System.out.println("a is big");

else if (b > a && b>c ){

System.out.println("B is big");

else {

System.out.println("c2 is big");

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 4

AIM:
Write a program in Java to find second maximum of n numbers without using
arrays.

PROGRAM:
ublic class Practical4
P

public static void main(String args[])

int n1=40,n2=9000,n3=20,n4=60,n5=21;

int m1,m2,m3,m4,largest,secondLargest,thirdLargest;

System.out.println("5 No.s:\n"+" n1="+n1+" n2="+n2+" n3=


"+n3+" n4="+n4+" n5="+n5);

largest=max1(n1,n2,n3,n4,n5);

System.out.println("Largest="+largest);

if(largest==n1)

n1=n2;
n2=n3;

n3=n4;

n4=n5;

else if(largest==n2)

n1=n1;

n2=n3;

n3=n4;

n4=n5;

Government Polytechnic, Porbandar


Page: JAVA (3350704)

else if(largest==n3)

n1=n1;

n2=n2;

n3=n4;

n4=n5;

else if(largest==n4)

n1=n1;
n2=n2;

n3=n3;

n4=n5;

else if(largest==n5)

n1=n1;

n2=n2;

n3=n3;

n4=n4;

secondLargest=max2(n1,n2,n3,n4);

System.out.println("2nd Largest="+secondLargest);

static int max2(int a,int b,int c,int d)

int m1,m2,m3;

m1=max(a,b);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

m2=max(m1,c);

m3=max(m2,d);

return m3;

static int max1(int n1,int n2, int n3,int n4,int n5)

int m1,m2,m3,m4,m5,l;

m1=max(n1,n2);

m2=max(n3,n4);

m3=max(m1,n5);

m4=max(m2,n5);
l=max(m3,m4);

return l;

static int max(int a,int b)

if(a>b)

return a;

else

return b;

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 5

AIM:
Write a program in Java to reverse the digits of a number using while loop.

PROGRAM:
import java.util.Scanner;

public class Practical5

public static void main(String args[])

System.out.println(" enter number :");

int number=new Scanner(System.in).nextInt();

int reverse=reverse(number);

System.out.println("Reverse of nmber:"+number +" is "+ rev


erse(number));

public static int reverse(int number)

int reverse = 0;
int remainder =0;

while(number>0)

remainder = number%10;

reverse = reverse*10+remainder;

number = number/10;

return reverse;

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 6

AIM:
Write a program in Java to convert number into words & print it.

PROGRAM:
mport java.util.Scanner;
i

public class practical6

public static void main(String[] args)

int number = 0;

Scanner scanner = new Scanner(System.in);

System.out.println("Please type a number(max upto 9 digits)");

try {

// read the number

number = scanner.nextInt();

if (number == 0)

System.out.print("Number in words: Zero");


}

else

System.out.print("Number in words: " + numberToWord(number


));

catch (Exception e)

System.out.println("Please enter a valid number");

Government Polytechnic, Porbandar


Page: JAVA (3350704)

scanner.close();

private static String numberToWord(int number) {

String words = "";

String unitsArray[] = { "zero", "one", "two", "three", "fo


ur", "five", "six",

"seven", "eight", "nine", "ten", "eleven", "


twelve",

"thirteen", "fourteen", "fifteen", "sixteen"


, "seventeen",

"eighteen", "nineteen" };
String tensArray[] = { "zero", "ten", "twenty", "thirty", "for
ty", "fifty",

"sixty", "seventy", "eighty", "ninety" };

if (number == 0)

return "zero";

if (number < 0)

String numberStr = "" + number;

numberStr = numberStr.substring(1);

return "minus " + numberToWord(Integer.parseInt(numberS


tr));

Government Polytechnic, Porbandar


Page: JAVA (3350704)

if ((number / 1000000) > 0)

words += numberToWord(number / 1000000) + " million ";

number %= 1000000;

if ((number / 1000) > 0)

words += numberToWord(number / 1000) + " thousand ";

number %= 1000;
}

if ((number / 100) > 0)

words += numberToWord(number / 100) + " hundred ";

number %= 100;

if (number > 0)

if (number < 20)

words += unitsArray[number];

else

Government Polytechnic, Porbandar


Page: JAVA (3350704)

words += tensArray[number / 10];

if ((number % 10) > 0)

words += "-" + unitsArray[number % 10];

return words;

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 7

AIM:
Write programs in Java to use Wrapper class of each primitive data types.

PROGRAM:
class Practical7

public static void main(String args[])

Integer iOb = new Integer(100);

int i=iOb.intValue();

System.out.println(i+ " "+ iOb);

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 8

AIM:
Write a program in Java to multiply two matrix.

PROGRAM:
mport java.util.Scanner;
i

public class Practical8

private static Scanner sc;

public static void main(String[] args) {

int i, j, rows, columns;

sc= new Scanner(System.in);

System.out.println("\n Enter Multiplication Matrix Rows &C


olumns : ");

rows = sc.nextInt();

columns = sc.nextInt();

int[][] arr1 = new int[rows][columns];

int[][] arr2 = new int[rows][columns];

System.out.println("\n Enter the First Multiplication Matr


ix Items : ");

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

for(j = 0; j < columns; j++) {

arr1[i][j] = sc.nextInt();

System.out.println("\n Enter the Second Multiplication Mat


rix Items : ");

Government Polytechnic, Porbandar


Page: JAVA (3350704)

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

for(j = 0; j < columns; j++) {

arr2[i][j] = sc.nextInt();

System.out.println("\n-----The Multiplication of two Matri


x----- ");

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

for(j = 0; j < columns; j++) {

System.out.format("%d \t", (arr1[i][j] * arr2[i]


[j]));

}
System.out.println("");

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 9

AIM:
Write a static block which will be executed before main( ) method in a class.

PROGRAM:
public class Practical9

static

System.out.println("Inside static block.");

public static void main(String[] args)

System.out.println("Inside main method.");

}
OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 10

AIM:
Write a program in Java to demonstrate use of this keyword. Check whether this
can access the private members of the class or not.

PROGRAM:
public class Practical10

public static void main(String[] args)

Test obj1 = new Test();

obj1.setdata(5);

obj1.getdata();

class Test

private int n;

void setdata(int n)

this.n = n; //accessing private member (n) using this keyword


.

void getdata()

System.out.println("n=" + n);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 11

AIM:
Write a program in Java to develop overloaded constructor. Also develop the copy
constructor to create a new object with the state of the existing object.

PROGRAM:
class Box {

int length;

int width;

int height;

Box()

System.out.println("Inside Default Constructor");

length = 10;

width = 10;

height = 10;

Box(int l, int w,int h)

System.out.println("Inside Parameterized Constructor");

length = l;

width = w;

height = h;

Box(Box b)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

System.out.println("Inside Copy Constructor");

length = b.length;

width = b.width;

height = b.height;

void volume()

int vol = length * width * height;

System.out.println("Volume of the Box: " + vol );

public class p11

public static void main(String[] args)

Box b1= new Box();

b1.volume();

Box b2= new Box(5,5,10);

b2.volume();

Box b3= new Box(b1);

b3.volume();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 12

AIM:
Write a program in Java to demonstrate the use of private constructor and also
write a method which will count the number of instances created using default
constructor only.

PROGRAM:
class Box

int length;

int width;

int height;

static int count=0;

Box()

length = 10;

width = 10;

height = 10;

Box.count_instances();

Box(int l, int w,int h)

length = l;

width = w;

height = h;

Government Polytechnic, Porbandar


Page: JAVA (3350704)

static void count_instances()

count++;

public class p12

public static void main(String[] args)

Box b1 = new Box();

Box b2 = new Box();

System.out.println("No of Objects Created: " + Box.count );

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 13

AIM:
Write a program in Java to demonstrate the use of 'final' keyword in the field
declaration. How it is accessed using the objects.

PROGRAM:
class FinalDemo

final double PI=3.14159;

final void display()

System.out.println("PI : " + PI);

public class p13

public static void main(String[] args)

FinalDemo obj = new FinalDemo();

obj.display();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 14

AIM:
Develop minimum 4 program based on variation in methods i.e. passing by value,
passing by reference, returning values and returning objects from methods.

PROGRAM:
class PBV {

int i;

void set_data(int a) {

i=a;

void display()

System.out.print("i : " + i);

public class Pactical14

public static void main(String[] args)

PBV obj = new PBV();

obj.set_data(5);

obj.display();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 15

AIM:
Write a program in Java to demonstrate single inheritance, multilevel inheritance
and hierarchical inheritance.

PROGRAM:
import java.util.*;

class A

public void PrintA()

System.out.println("This is Message from class A");

class B extends A

public void PrintB()

System.out.println("This is Message from class B");

class C extends B

public void PrintC()

System.out.println("This is Message from class C");

class D extends A

Government Polytechnic, Porbandar


Page: JAVA (3350704)

public void PrintD()

System.out.println("This is Message from class D");

class U4P1

public static void main(String args[])

B B1 = new B();

C C1 = new C();

D D1 = new D();

B1.PrintB();

C1.PrintC();

D1.PrintD();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 16

AIM:
Create a class to find out whether the given year is leap year or not. (Use
inheritance for this program).

PROGRAM:
import java.util.Scanner;

public class Practical16{

public static void main(String[] args) {

System.out.println("Thanki Shivam");

System.out.print("ENTER YEAR :- ");

int number=new Scanner(System.in).nextInt();

int year = number;

boolean leap = false;

if (year % 4 == 0) {

if (year % 100 == 0) {

if (year % 400 == 0)

leap = true;

else

leap = false;

else

leap = true;

else

leap = false;

if (leap)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

System.out.println(year + " is a leap year.");

else

System.out.println(year + " is not a leap year.");

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 17

AIM:
Write an application that illustrates how to access a hidden variable. Class A
declares a static variable x. The class B extends A and declares an instance
variable x. display() method in B displays both of these variables.

PROGRAM:
import java.util.*;

class A

static int x;

class B extends A

int x;

B(int a,int b)

super.x = a; //super.x refers variable x of class A

x = b; // x refers to variable x of class B

void display()

//super.x prints value of variable x of class A

System.out.println("X of A :" + super.x);

//x prints value of variable x of class B

System.out.println("X of B :" + x);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

class U4P3

public static void main(String args[]) {

B obj = new B(70,57);

obj.display();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 18

AIM:
Write a program in Java in which a subclass constructor invokes the constructor of
the super class and instantiate the values.

PROGRAM:
class A

int x;

A(int a)

x=a;

class B extends A

int y;

B(int a,int b)

super(a);

y = b;

void display()

System.out.println("X :" + x);

System.out.println("Y :" + y);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

public class U4P4

public static void main(String[] args)

B obj = new B(2,4);

obj.display();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 19

AIM:
Write a program that illustrates interface inheritance. Interface P12 inherits from
both P1 and P2. Each interface declares one constant and one method. The class Q
implements P12. Instantiate Q and invoke each of its methods. Each method
displays one of the constants.

PROGRAM:
import java.util.*;

interface P1

int I = 10;

void showI();

interface P2

int J = 30;

void showJ();

interface P12 extends P1, P2

int K = 50;

void showK();

class Q implements P12

public void showI()

System.out.println("I : " + I);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

public void showJ()

System.out.println("J : " + J);

public void showK()

System.out.println("K : " + K);

class U4P5

public static void main(String[] args) {

Q obj = new Q();

obj.showI();

obj.showJ();

obj.showK();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 20

AIM:
Write an application that illustrates method overriding in the same package and
different packages. Also demonstrate accessibility rules in inside and outside
packages.

PROGRAM:
import java.util.*;

class A

void show()

System.out.println("Inside Class-A");

}class B extends A

//Overriding method show of class A

void show()

System.out.println("Inside Class-B");

class U4P6

public static void main(String arg[])

B obj=new B();

obj.show(); //show() method of class-B will called.

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Create Package:
package p1;

public class Protection

public int n =74;

public int n_pub=19;

Inside:
import p1.*;

class inside

public static void main(String arg[])

Protection p1=new Protection();

System.out.println("n = "+p1.n);

System.out.println("n_pub = "+p1.n_pub);

Inside Output:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Outside:
import p1.*;

class outside

public static void main(String arg[])

Protection p1=new Protection();

System.out.println("n = "+p1.n);

System.out.println("n_pub = "+p1.n_pub);

Outside Output:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 21

AIM:
Describe abstract class called Shape which has three subclasses say Triangle,
Rectangle, Circle. Define one method area() in the abstract class and override this
area() in these three subclasses to calculate for specific object i.e. area() of
Triangle subclass should calculate area of triangle etc. Same for Rectangle and
Circle.

PROGRAM:
import java.util.*;

abstract class Shape

abstract void area();

class Triangle extends Shape

int base,height;

Triangle(int b,int h)

base=b;

height=h;

void area()

float ar = (0.5f)* (base*height);

System.out.println("Area of Triangle: "+ar);

class Rectangle extends Shape

Government Polytechnic, Porbandar


Page: JAVA (3350704)

int length,width;

Rectangle(int l,int w)

length=l;

width=w;

void area()

float ar = length*width;

System.out.println("Area of Rectangle: "+ar); }

class Circle extends Shape

int radius;

Circle(int r)

radius = r;

void area()

float ar = 3.14f * radius * radius; System.out.println("Area of Circle: "+ar);

class U4P7

public static void main(String[] args) {

Triangle t1 = new Triangle(2,4);

t1.area();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Rectangle r1 = new Rectangle(3,5);

r1.area();

Circle c1= new Circle(2);

c1.area();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 22

AIM:
Write a program in Java to demonstrate implementation of multiple inheritance
using interfaces.

PROGRAM:
interface A

void method1();

interface B

void method2();

class InterfaceDemo implements A , B

public void method1()

System.out.println("Inside Method-1");

public void method2()

System.out.println("Inside Method-2");

public class Example

Government Polytechnic, Porbandar


Page: JAVA (3350704)

public static void main(String[] args)

InterfaceDemo obj = new InterfaceDemo();

obj.method1();

obj.method2();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 23

AIM:
Write a program in Java to demonstrate use of final class.

PROGRAM:
import java.util.*;

final class A

int i;

void showI()

System.out.println("I : " + i);

// The following class is illegal.

// ERROR! Can't subclass A

class B extends A

int j;

void showJ()

System.out.println("J : " + j);

class Finalclass

public static void main(String[] args)

System.out.println("Thanki Shivam");

Government Polytechnic, Porbandar


Page: JAVA (3350704)

B obj = new B();

obj.i = 20;

obj.j = 30;

obj.showI();

obj.showJ();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 24

AIM:
Write a program in Java to develop user defined exception for 'Divide by Zero'
error.

PROGRAM:
final class A

int i;

void showI()

System.out.println("I : " + i);

// The following class is illegal.

// ERROR! Can't subclass A

class B extends A

int j;

void showJ()

System.out.println("J : " + j);

Government Polytechnic, Porbandar


Page: JAVA (3350704)

public class p24

public static void main(String[] args)

B obj = new B();

obj.i = 2;

obj.j = 3;

obj.showI();

obj.showJ();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 25

AIM:
Write a program in Java to demonstrate multiple try block and multiple catch
exception.

PROGRAM:
public class p25

public static void main(String[] args)

try

int a= 4/0;

try

int b[] = {1,2};

System.out.println(b[5]);

catch(ArrayIndexOutOfBoundsException e)

System.out.println("Array index is out of bound.");

catch(ArithmeticException e)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

System.out.println("Divide by zero.");

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 26

AIM:
Write an small application in Java to develop Banking Application in which user
deposits the amount Rs 1000.00 and then start withdrawing of Rs 400.00, Rs
300.00 and it throws exception "Not Sufficient Fund" when user withdraws Rs.
500 thereafter.

PROGRAM:
import java.util.*;

import java.io.*;

class Bank

float fund;

void deposit(float amount)

fund=amount;

void withdraw(float money) throws Exception

float newFund=fund-money;

if(newFund<500)

throw new Exception("Not Sufficient Fund");

else

Government Polytechnic, Porbandar


Page: JAVA (3350704)

fund=newFund;

System.out.println("Balance After Withdraw : "+fund);

public static void main(String arg[])

Bank b=new Bank();

b.deposit(1000.00f);

try

float money;

Scanner sc=new Scanner(System.in);

System.out.println("Enter Your Amount for withdraw


: ");

money=sc.nextInt();

System.out.println("Withdrawing amount : "+money);

b.withdraw(money);

catch(Exception e)

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

Government Polytechnic, Porbandar


Page: JAVA (3350704)

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 27

AIM:
Write a program that executes two threads. One thread displays “Thread1” every
2,000 milliseconds, and the other displays “Thread2” every 4,000 milliseconds.
Create the threads by extending the Thread class.

PROGRAM:
class NewThread extends Thread

NewThread(String threadname)

super(threadname);

public void run()

if( getName().equals("Thread1")==true)

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

System.out.println("Thread1");

try

Thread.sleep(2000);

catch(InterruptedException e)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

System.out.println("Exception Occurred.");

else

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

System.out.println("Thread2");

try

Thread.sleep(4000);

catch(InterruptedException e)

System.out.println("Exception Occurred.");

public class p27

public static void main(String[] args)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

NewThread t1 = new NewThread("Thread1");

NewThread t2 = new NewThread("Thread2");

t1.start();

t2.start();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 28

AIM:
Write a program that executes two threads. One thread will print the even numbers
and the another thread will print odd numbers from 1 to 50.

PROGRAM:
class NewThread extends Thread

NewThread(String threadname)

super(threadname);

public void run()

if( getName().equals("Odd")==true)

for(int i=1;i<=50;i=i+2)

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

try

Thread.sleep(1000);

catch(InterruptedException e)

System.out.println("Exception Occurred.");

Government Polytechnic, Porbandar


Page: JAVA (3350704)

else

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

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

try

Thread.sleep(1000);

catch(InterruptedException e)

System.out.println("Exception Occurred.");

public class p28

public static void main(String[] args)

NewThread t1 = new NewThread("Odd");

NewThread t2 = new NewThread("Even");

t1.start();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

t2.start();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 29

AIM:
Write a program in Java to demonstrate use of synchronization of threads when
multiple threads are trying to update common variable.

PROGRAM:
class Counter

int c=0;

synchronized void increment()

c++;

try

Thread.sleep(1000);

catch(InterruptedException e)

System.out.println("caught: " + e);

System.out.println("C = " + c);

class NewThread extends Thread

Counter obj;

NewThread(Counter o)

Government Polytechnic, Porbandar


Page: JAVA (3350704)

obj = o;

public void run()

obj.increment();

public class p29

public static void main(String[] args)

Counter c1 = new Counter();

NewThread t1 = new NewThread(c1);

t1.start();

NewThread t2 = new NewThread(c1);

t2.start();

NewThread t3 = new NewThread(c1);

t3.start();

OUTPUT:

Government Polytechnic, Porbandar


Page: JAVA (3350704)

Practical - 30

AIM:
Write a program in Java to create, write, modify, read operations on a Text file.

PROGRAM:
import java.io.*;

public class p30

public static void main(String[] args)

try

// Creating new Text file

File file = new File("E:/newfile.txt");

if (!file.exists())

file.createNewFile();

System.out.println("File created Successfully.");

// Writing to new Text file

FileOutputStream fout=new FileOutputStream("E:\\newfile.txt");

String s="India is Great.";

byte b[]=s.getBytes();

fout.write(b);

fout.close();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

System.out.println("Writing Complete!");

//Reading from Text file

FileInputStream fin = new FileInputStream("E:\\newfile.txt");

int i;

while((i=fin.read())!=-1)

System.out.print((char)i);

fin.close();

// Modifying Text file

fout=new FileOutputStream("E:\\newfile.txt");

s="I love India.";

b=s.getBytes();

fout.write(b);

fout.close();

System.out.println("\n Modification Complete!");

//Reading from Text file

fin = new FileInputStream("E:\\newfile.txt");

while((i=fin.read())!=-1)

System.out.print((char)i);

fin.close();

Government Polytechnic, Porbandar


Page: JAVA (3350704)

catch (IOException e)

System.out.println("I/O Exception occurred.");

OUTPUT:

Government Polytechnic, Porbandar

You might also like