You are on page 1of 52

Set - A

Table of Contents
Sr.
No.
1.

2.

3.
4.
5.
6.
7.
8.

9.

10.

11.

Experiment Description

Experiment Page
Remarks/Signature
Date
No.

Introduction
Introduction About Java
The Java Buzzwords: Simple, Secure,
Portable, Object-oriented, Robust,
Multithreaded, Architecture-neutral,
Interpreted, High performance, Distributed,
Dynamic
Basic Java Programs
A Program To Generate And Display n
Fibonacci Numbers
A Program To Find The Greatest Common
Divisor Of Two Numbers
A Program To Reverse The Digits Of A
Number
A Program To Remove Duplicates From An
Array
A Program To Search For A Number In A
List Of Numbers Using Binary Search
A Program To Find
sin(x) = x/1! x3/3! + x5/5!
Class And Object
A program to Create a class Rectangle. The
class has attributes length and width, each
which defaults to 1. It has methods that
calculate the perimeter and the area of the
rectangle. It has set and get methods for both
length and width. The set method should
verify that length and width are each floating
point numbers larger than 0.0 and less than
20.0. Create a class to test this Rectangle class
A program to create a class IntegerSet. Each
IntegerSet object can hold integers in the
range 0-100. The set is represented by an
array of Booleans. Array element a[i] is true if
integer I is present in the set and false
otherwise. The no argument constructor
initializes the array to the empty set. Provide
methods for union, intersection to create a
new set. Also provide method insertElement
and deleteElement to insert and delete
elements from the set
Inheritance
Program to create a class MyPoint to represent
a point with x-coordinates and y-coordinates.
The class contains:

Set - A
Two data fields x and y that represents the
coordinates
A no-args constructor that creates a point
(0,0)
A constructor that constructs a point with
specified coordinates
Two get (accessor) methods for data fields
x and y respectively
A method named distance that returns the
distance from this point to another point of the
MyPoint type
A method named distance that returns the
distance between this point to another point
with specified x- and y- coordinates.

12.

13.
14.

15.

Extend the class MyPoint to create a class


ThreeDPoint with the following additional
features:
A data field named z that represents the zcoordinate
A no-args constructor that creates a point
(0,0,0)
A constructor that constructs a point with
three specified coordinates
A get method for the z value
Override the distance method to return the
distance between two points in the three
dimensional space
Program to create an interface called Exam
with a method (public) percent_calc().
Create a class called Student with fields
(private) name, roll_no, mark1, mark2. And
it has a parameterized constructor and a public
method display().Create another class Result
which inherits from Student and implements
the interface Exam includes a constructor. In
this class define the method percent_calc()
and call the method display() by super
keyword. Finally test your classes using a
driver class
Applets
An applet program to display the
multiplication table from user choice
An applet program to take input for the date of
birth of a person and display the age in terms
of years, months and days
Threads
A program to demonstrate that as a highpriority thread executes, it will delay the
execution of all lower-priority threads

Set-A

Page |1

INTRODUCTION ABOUT JAVA

Java is a high level Object oriented programming language. It was conceived by James
Gosling, Patrik Naughton, Chris Wrath, Ed Frank and Mike Sheridan at Sun Microsystems,
Inc (which has since been acquired by Oracle Corporation.) in 1991. It was initially called
oak but was renamed Java in 1995. Java technology is both platform and programming
language.
Java platform was initially developed to address the problems of building software for
networked consumer electronic devices e.g. washing machine, Refrigerator. Sun released
the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere
(WORA), providing no-cost run-times on popular platforms.
The primary impetus for Java was the need for platform independent (Architecture Neutral)
language that could be used to create software for various devices. In an attempt to find
such a solution, Gosling and others began work on a portable and platform independent
language. This effort ultimately led to the creation of Java.
The secondary impetus for Javas creation was World Wide Web. With the emergence of the
World Wide Web, Java was propelled to the forefront of computer language design, because
the Web too, demanded portable programs. The most striking feature of the language is that
it is a platform-neutral language.
On 13 November 2006, Sun released much of Java as free and open source software under
the terms of the GNU General Public License (GPL). On 8 May 2007, Sun finished the
process, making all of Java's core code free and open-source, aside from a small portion of
code to which Sun did not hold the copyright.

Java is simple, portable, Object Oriented, secure, robust, dynamic, interpreted,


multithreaded and distributed programming language.

Set-A

Page |2

THE JAVA BUZZWORDS


The author of Java have written an influential whit-paper that explains their goals and
accomplishment for describing Java, they used a standard set of buzzwords. They are as
below:

Simple

Object Oriented

Platform Independent

Secured

Robust

Architecture Neutral

Portable

Dynamic

Interpreted

High Performance

Multithreaded

Distributed

Simple: - Java is simple because,


Unlike C and C++, Java does not use pointers.
Looks familiar to existing programmers: related to C and C++.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
Removed many confusing and/or rarely used features. E.g. operator
overloading, explicit pointers etc.
Object Oriented: - Java is an object oriented language, which means we organize our
software as a combination of different types of objects that incorporates both data and
behaviour.

Set-A

Page |3

Platform Independent :- Java code can be run on multiple platforms. Java code is compiled
by the compiler and converted into Bytecode. Bytecode is an platform independent file,
which can be run on many platform. The Bytecode is interpreted by Java Virtual Machine on
whichever platform it is being run.
Secured:- Java is secured because,
There is no explicit pointer in Java.
Java programs runs inside Virtual Machine Sandbox.
During execution, Java programs uses runtime environment of its own.
Classloader: - Adds security by separating the packages for the class of the
local file system from those that are imported from network sources.
Bytecode Verifier: - Checks code fragments for illegal code that can violates
access rights to objects.

Robust: - Java has been designed for writing highly reliable or robust software. All the
following point makes Java robust
Java uses strong memory management.
There is lack of explicit pointers that avoids security problem.
There are Exception handling and type checking mechanism in Java.
Architecture Neutral :- Java compiler generates an architecture neutral object file , which
makes the compiled to be executable on many processors, with the presence of Java Run
Time.
Portable: - We may carry the java programs (Bytecode) to any platform without any
modification or changes.
Dynamic:- Java programs can carry extensive amount of run-time information that can be
used to verify and resolve accesses to objects at run-time. This makes it possible to
dynamically link code in safe and expedient manner.

Set-A

Page |4

Interpreted: - Java enables the creation of cross platform programs by compiling sourcecode into an intermediate representation called Java Bytecode. Java Bytecode is translated
(interpreted) on the fly to native machine instruction by JVM. The development process is
more rapid and analytical since the linking is an incremental and lightweight process. Thus,
Java is said to be interpreted.
High-Performance: - With the use of Just-In-Time Compiler, Java enables high performance.
Multithreaded :- With Javas multithreaded feature, it is possible to write programs that can
do many tasks simultaneously. The main advantage of Multithreading is that it shares the
same memory area.
Distributed:- Java is designed as a distributed language for creating applications networks.
RMI and EJB are used for creating distributed application. By distributed programming, we
may access files by calling the methods from any machine on the networks (Internet).

Set-A

Page |5

A program to generate and display n Fibonacci Numbers


File Name:- Fibonacci.java
Source code:import java.io.*;
class Fibonacci{
public static void main(String args[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int num;
System.out.print("\nEnter Limit of series :-> ");
num = Integer.parseInt(br.readLine()); //Used as Limit to Display Number
System.out.println("\n#######################Fibonacci
Series#######################\n");
long num1,num2=0,num3=1;
for(int i=1; i<=num; i++) //Fibonacci Number generator loop
{
System.out.print(" "+num3+" ");
num1 = num2;
num2 = num3;
num3 = num1+num2;
}
}catch(Exception e){
System.out.println("\n\t"+e);
}
}
}

Set-A

Page |6

Output:-

C:\Users\DEll\Java>java Fibonacci

Enter Limit of series :-> 19

#######################Fibonacci Series#######################

1 1 2 3 5 8 13 21 34

Set-A

Page |7

A Program to find the Greatest Common Divisor of two numbers


File Name: - GCD.java
Source code:import java.io.*;
class GCD{
public static void main(String args[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter first number :-> ");
int num1 = Integer.parseInt(br.readLine());
System.out.print("\nEnter second number :-> ");
int num2 = Integer.parseInt(br.readLine());
int min;

if(num1>num2)
min = num2;
else
min = num1;

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


{
if(num1%i == 0 && num2%i == 0)
{
System.out.println("\n\tGCD : " +i);
break;
}
}

Set-A

Page |8
}catch(Exception e){
System.out.println("\n\t"+e);
}

}}

Output:C:\Users\DEll\Java>java GCD
Enter first number :-> 8
Enter second number :-> 4
GCD: 4

Set-A

Page |9

A program to reverse the digits of a number

File Name: - Reverse.java


Source code:import java.io.*;
class Reverse{
public static void main(String args[]){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.print("\n Enter number :-> ");
int num = Integer.parseInt(br.readLine());
int Dnum = num;
int rev =0,rem;
if(num >9){
while(Dnum > 0){

rem = Dnum%10;
rev = rev*10+rem;
Dnum = Dnum/10;
}
System.out.println("\n\tReversed Number = "+rev);
}else{
System.out.println("\n\tInvalid Input:- Number Must be larger than one digit !");
}
}catch(Exception e){
System.out.println(e);
}

Set-A

P a g e | 10

}}

Output:-

C:\Users\DEll\Java>java Reverse
Enter number :-> 476
Reversed Number = 674

Set-A

P a g e | 11

A program to remove duplicates from an array

File Name: - RemoveDuplicate.java


Source code:import java.io.*;
class RemoveDuplicate{
public static void main(String args[]){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
int array[] = new int[10];
System.out.println("\nEnter 10 elements in array\n");
for(int i = 0; i < 10; i++){
System.out.print("array["+i+"] = ");
array[i] = Integer.parseInt(br.readLine());
}

/*Removing Dublicates from array */


int dup = 0,cout=0;
int Narray[] = new int[10];
for (int i = 0; i < 10; i++) {
dup = 0;
for (int j = i + 1; j < 10;j++) {
if (array[i] == array[j]) {
dup = 1;
break;
}
}

Set-A

P a g e | 12
if(dup == 0){
Narray[cout] = array[i];
cout++;
}

}
/*Printing Refined array */

int len = cout;


System.out.println("\n\t\tRefined Array");
for(int i=0;i<len;i++){
System.out.println("\t\tarray["+i+"] = "+Narray[i]);
}
}catch(Exception e){
System.out.println("\n\t"+e);
}
}}

Set-A

P a g e | 13

Output:-

C:\Users\DEll\Java>java RemoveDuplicate
Enter 10 elements in array
array[0] = 4
array[1] = 5
array[2] = 3
array[3] = 9
array[4] = 8
array[5] = 7
array[6] = 2
array[7] = 1
array[8] = 3
array[9] = 4

Refined Array
array[0] = 5
array[1] = 9
array[2] = 8
array[3] = 7
array[4] = 2
array[5] = 1
array[6] = 3
array[7] = 4

Set-A

P a g e | 14

A program to search for a number in a list of numbers using binary search

File Name: - binary_search.java


Source code:import java.io.*;
class binary_search{
public static void main(String args[]){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
int arr[] = new int[10];
System.out.print("\n\t\tEnter Ten numbers in Array");
System.out.println("\n Warning! :- Numbers should be in ascending order and they should
not same\n");
for(int i =0;i<10;i++){
System.out.print("arr["+i+"] = ");
arr[i] = Integer.parseInt(br.readLine());
}
System.out.print("\nEnter the Number to be searched :-> ");
int sNum = Integer.parseInt(br.readLine());
/* Searching 'sNum' in array */
int p=-1, mid,l=0,u=9;
while(l<=u){
mid = (l+u)/2;
if(arr[mid] == sNum){
p = mid;
break;
}
else if(sNum>arr[mid]){

Set-A

P a g e | 15
l = mid+1;
}
else if(sNum<arr[mid]){
u = mid-1;
}

}
if(p==-1)
{
System.out.println("Number Does not Exist");
}
else{
System.out.println("Number Exist in the array index at "+p);
}
}catch(Exception e){
System.out.println("\n\t"+e);
}
}}

Set-A

P a g e | 16

Output:C:\Users\DEll\Java>javac binary_search.java
C:\Users\DEll\Java>java binary_search
Enter Ten numbers in Array
Warning! :- Numbers should be in ascending order and they should not same
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
arr[4] = 4
arr[5] = 5
arr[6] = 6
arr[7] = 7
arr[8] = 8
arr[9] = 9

Enter the Number to be searched :-> 5


Number Exist in the array index at 5

Set-A

P a g e | 17

A program to find:sin(x) = x/1! x3/3! + x5/5!

File Name: - Sin_x.java


Source code:import java.io.*;
import java.lang.Math;

class Sin_x{
public static void main(String args[])
{
try{
double x,n,f,m=1,sum=0;
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

System.out.print("\nEnter the value of X -> ");


x = Integer.parseInt(br.readLine());
System.out.print("\nEnter the last limit -> : ");
n = Integer.parseInt(br.readLine());

for(double i=1.0;i<=n;i=i+2)
{
f=1;
for(double j=1.0;j<=i;j++)
{
f=f*j;
}

Set-A

P a g e | 18
if(m==1)
{
sum=(sum+ (Math.pow(x,i))/f) ;
m=0;
}
else
{
sum=(sum- (Math.pow(x,i))/f) ;
m=1;
}
}
System.out.printf("\n\tSum = %.5f\n",sum);
}catch(Exception e){
System.out.println("\n\t"+e);
}

}}
Output:-

C:\Users\DEll\Java>javac Sin_x.java
C:\Users\DEll\Java>java Sin_x
Enter the value of X -> 2
Enter the last limit -> : 5
Sum = 0.93333

Set-A

P a g e | 19

A program to create a class Rectangle. The class has attributes length


and width, each which defaults to 1. It has methods that calculate the
perimeter and the area of the rectangle. It has set and get methods for
both length and width. The set method should verify that length and width
are each floating point numbers larger than 0.0 and less than 20.0. Create
a class to test this Rectangle class

File Name: - testRect.java


Source code:import java.io.*;

class rectangle{
double length;
double width;

rectangle(){
length = 1;
width = 1;
}

double getWidth(){
return width;
}

double getLength(){
return length;
}

Set-A

P a g e | 20

int SetLength(double l){


if(l>0.0 && l<20.0)
{
length = l;

return 0;
}else{
System.out.println("\n\tInvalid Length");
return 1;
}
}

int SetWidth(double w){


if(w>0.0 && w<20.0)
{
width = w;
return 0;
}else{
System.out.println("\n\tInvalid Width");
return 1;
}
}

double perimeter(){
return 2*(getWidth()+getLength());
}

Set-A

P a g e | 21

double area(){
return getWidth()*getLength();
}
}

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

rectangle obj = new rectangle();


double wid,len;
int ret_wid, ret_len;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try{
System.out.print("\n Enter Width of Rectangle -> ");
wid = Double.parseDouble(br.readLine());
System.out.print("\n Enter Length of Rectangle -> ");
len = Double.parseDouble(br.readLine());

ret_wid = obj.SetWidth(wid);
ret_len = obj.SetLength(len);
if(ret_wid == 1 || ret_len==1){
System.exit(0);
}
else{
double perimeter = obj.perimeter();
double area = obj.area();

Set-A

P a g e | 22
System.out.println("\n Perimeter = "+perimeter);
System.out.println("\n Area = "+area);

}catch(Exception e){
System.out.println("\n\t"+e);
}
}}

Output:C:\Users\DEll\Java>java testRect

Enter Width of Rectangle -> 5

Enter Length of Rectangle -> 10

Perimeter = 30.0

Area = 50.0

Set-A

P a g e | 23

A program to create a class IntegerSet. Each IntegerSet object can hold


integers in the range 0-100. The set is represented by an array of
Booleans. Array element a[i] is true if integer I is present in the set and
false otherwise. The no argument constructor initializes the array to the
empty set. Provide methods for union, intersection to create a new set.
Also provide method insertElement and deleteElement to insert and delete
elements from the set.

File Name: - Integer_Set.java


Source code:import java.io.*;

class IntegerSet
{
private boolean a[] = new boolean[10];

public IntegerSet()
{
for(int i=0; i<10; i++)
{
a[i] = false;
}
}

public void insertElement(int j)


{
if(a[j] == false)
a[(int) (j)] = true;
else

Set-A

P a g e | 24
{
System.out.printf("\nIndex %d is already true", j);
System.exit(0);
}

public void deleteElement(int j)


{
if(a[j] == true)
a[(int) (j)] = false;
else
{
System.out.printf("\nIndex %d is already false", j);
System.exit(0);
}
}

public void storeElement(IntegerSet I, int j)


{
if(a[j] == true)
I.a[(int) (j)] = true;
}

public IntegerSet union(IntegerSet I1, IntegerSet I2) throws IOException


{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String inS1, inS2, inS3, inS4;

Set-A

P a g e | 25
int opt, n, index_i, index_d, index_i1;
IntegerSet I3 = new IntegerSet();

System.out.printf("\n\n\t\t*******DETAILS OF FIRST SET*******\n");


System.out.printf("\nHow many times you want to put the value(s)?: ");
inS1 = stdin.readLine();
n = Integer.parseInt(inS1);

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


{
System.out.printf("\nPlease enter the position to where you want to insert
the value: ");
inS2 = stdin.readLine();
index_i1 = Integer.parseInt(inS2);
I1.insertElement(index_i1);
for(int j=0; j < 10; j++)
{
I1.storeElement(I3, j);
}
}
System.out.printf("\n\n\t\t*** FIRST SET ***\n");
I1.display();

System.out.printf("\n\n\t*******DETAILS OF SECOND SET*******\n");


System.out.printf("\nHow many times you want to put the value(s)?: ");
inS3 = stdin.readLine();
n = Integer.parseInt(inS3);

Set-A

P a g e | 26
for(int i=0; i < n; i++)
{
System.out.printf("\nPlease enter the position to where you want to insert

the value: ");


inS4 = stdin.readLine();
index_i1 = Integer.parseInt(inS4);
I2.insertElement(index_i1);
for(int j=0; j < 10; j++)
{
I2.storeElement(I3, j);
}
}
System.out.printf("\n\n\t\t*** SECOND SET ***\n");
I2.display();
System.out.printf("\n\n\t\t*** UNION OF FIRST AND SECOND SET ***\n");
I3.display();
return (I3);
}

public IntegerSet intersection(IntegerSet I1) throws IOException


{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String inS1, inS2, inS3, inS4;
int opt, n, index_i, index_d, index_i1, index_i2;
IntegerSet I2 = new IntegerSet();

for(int j=0; j < 10; j++)


{

Set-A

P a g e | 27
if(a[j] == true && I1.a[j] == true)
{
I2.a[(int) (j)] = true;
}
}
return (I2);

public void display()


{
for( int i = 0; i < 10; i++ )
System.out.printf("\nIndex %d: %s", i, String.valueOf(a[i]));
}
};

class Integer_Set
{
/*main() method*/
public static void main(String args[])throws IOException
{
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
String inS1, inS2, inS3, inS4;
int opt, n, index_i, index_d, index_i1;
IntegerSet I1 = new IntegerSet();
IntegerSet I2 = new IntegerSet();
IntegerSet I3 = new IntegerSet();

Set-A

P a g e | 28
do
{
System.out.println("\n\n\t\tPlease select your option.\n");
System.out.printf("\n\tPress 1 for INSERT ELEMENT.\n");
System.out.printf("\n\tPress 2 for DELETE ELEMENT.\n");
System.out.printf("\n\tPress 3 for UNION OF TWO SETS.\n");
System.out.printf("\n\tPress 4 for INTERSECTION OF TWO SETS.\n");
System.out.printf("\n\tPress 5 for EXIT.\n");
System.out.print("\nEnter your choice ->");
inS1=stdin.readLine();
opt=Integer.parseInt(inS1);

switch(opt)
{
case 1:
{
System.out.printf("\nHow many times you want to put the
value(s)?: ");
inS1 = stdin.readLine();
n = Integer.parseInt(inS1);

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


{
System.out.printf("\nPlease enter the position to
where you want to insert the value: ");
inS2 = stdin.readLine();
index_i = Integer.parseInt(inS2);
I1.insertElement(index_i);

Set-A

P a g e | 29
}
I1.display();
break;
}

case 2:
{
System.out.printf("\nPlease enter the position from where
you want to delete the value: ");
inS1 = stdin.readLine();
index_d = Integer.parseInt(inS1);
I1.deleteElement(index_d);
I1.display();
break;
}

case 3:
{
I3.union(I1, I2);
break;
}

case 4:
{
System.out.printf("\nHow many times you want to put the
value(s)?: ");
inS1 = stdin.readLine();
n = Integer.parseInt(inS1);

Set-A

P a g e | 30

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


{
System.out.printf("\nPlease enter the position to
where you want to insert the value: ");
inS2 = stdin.readLine();
index_i = Integer.parseInt(inS2);
I1.insertElement(index_i);
}

System.out.printf("\nHow many times you want to put the


value(s)?: ");
inS1 = stdin.readLine();
n = Integer.parseInt(inS1);

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


{
System.out.printf("\nPlease enter the position to
where you want to insert the value: ");
inS2 = stdin.readLine();
index_i = Integer.parseInt(inS2);
I2.insertElement(index_i);
}
I3 = I2.intersection(I1);
I3.display();
break;
}

case 5:

Set-A

P a g e | 31
{
System.out.printf("\nProgram Terminated...!\n");
System.exit(0);
break;
}

default:
System.out.printf("\nInvalid Input...!\n");
}
}while(opt!=5);
}
}
Output:C:\Users\DEll\Java >java Integer_Set
Please select your option.
Press 1 for INSERT ELEMENT.
Press 2 for DELETE ELEMENT.
Press 3 for UNION OF TWO SETS.
Press 4 for INTERSECTION OF TWO SETS.
Press 5 for EXIT.
Enter your choice ->1
How many times you want to put the value(s)?: 2
Please enter the position to where you want to insert the value: 3
Please enter the position to where you want to insert the value: 5
Index 0: false
Index 1: false
Index 2: false

Set-A

P a g e | 32

Index 3: true
Index 4: false
Index 5: true
Index 6: false
Index 7: false
Index 8: false
Index 9: false

Please select your option.


Press 1 for INSERT ELEMENT.
Press 2 for DELETE ELEMENT.
Press 3 for UNION OF TWO SETS.
Press 4 for INTERSECTION OF TWO SETS.
Press 5 for EXIT.
Enter your choice ->5

Set-A

P a g e | 33

Create a class MyPoint to represent a point with x-coordinates and ycoordinates. The class contains:
Two data fields x and y that represents the coordinates
A no-args constructor that creates a point (0,0)
A constructor that constructs a point with specified coordinates.
Two get (accessor) methods for data fields x and y respectively
A method named distance that returns the distance from this
point to another point of the MyPoint type
A method named distance that returns the distance between this
point to another point with specified x- and y- coordinates.
Extend the class MyPoint to create a class ThreeDPoint with the
following additional features:
A data field named z that represents the z-coordinate
A no-args constructor that creates a point (0,0,0)
A constructor that constructs a point with three specified
coordinates.
A get method for the z value
Override the distance method to return the distance between two
points in the three dimensional space.
-------------------------------------------------------------------------------------------------------------------------------------File Name: - testCoordinate.java
Source code:import java.io.*;

class MyPoint{

private int X,Y;

MyPoint(){
X = 0;
Y = 0;
}

Set-A

P a g e | 34
MyPoint(int x, int y){
X = x;
Y = y;
}

int retX(){
return X;
}

int retY(){
return Y;
}

double Distance(MyPoint obj2){


int X2,Y2;
double dis;

X2 = obj2.retX();
Y2 = obj2.retY();

dis = Math.sqrt(Math.pow((X2 - X),2) + Math.pow((Y2 - Y),2) );


return dis;
}

class ThreeDPoint extends MyPoint{

Set-A

P a g e | 35

private int Z;

ThreeDPoint(){
super();
Z = 0;
}

ThreeDPoint(int x, int y, int z){


super(x,y);
Z = z;
}

int retZ()
{
return Z;
}

double Distance(ThreeDPoint obj2){


int X1,Y1,X2,Y2,Z1,Z2;
double dis;

X1 = this.retX();
Y1 = this.retY();
X2 = obj2.retX();
Y2 = obj2.retY();
Z1 = Z;
Z2 = obj2.Z;

Set-A

P a g e | 36

dis = Math.sqrt(Math.pow((X2-X1),2) + Math.pow((Y2-Y1),2) + Math.pow((Z2 Z1),2));


return dis;
}

class testCoordinate{
public static void main(String args[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("\n\t\t\tTwo Dimensional Distance Calculation");


System.out.println("\n|---Input for First Point----|");
System.out.println("|

|");

System.out.print("|Enetr x:-> ");


int x1 = Integer.parseInt(br.readLine());
System.out.print("|Enetr y:-> ");
int y1 = Integer.parseInt(br.readLine());
System.out.println("|----------------------------|");

System.out.println("\n|---Input for Second Point----|");


System.out.println("|

|");

System.out.print("|Enetr x:-> ");


int x2 = Integer.parseInt(br.readLine());

Set-A

P a g e | 37
System.out.print("|Enetr y:-> ");
int y2 = Integer.parseInt(br.readLine());
System.out.println("|-----------------------------|");

MyPoint Myobj1 = new MyPoint(x1,y1);


MyPoint Myobj2 = new MyPoint(x2,y2);

double dis = Myobj1.Distance(Myobj2);


System.out.printf("\n\tDistance between (%d,%d) and (%d,%d) is %.2f\n",x1,y1,x2,y2,dis);

System.out.println("\n\t\t\tThree Dimensional Distance


Calculation");
System.out.println("\n|---Input for First Point----|");
System.out.println("|

|");

System.out.print("|Enetr x:-> ");


x1 = Integer.parseInt(br.readLine());
System.out.print("|Enetr y:-> ");
y1 = Integer.parseInt(br.readLine());
System.out.print("|Enetr z:-> ");
int z1 = Integer.parseInt(br.readLine());
System.out.println("|----------------------------|");

System.out.println("\n|---Input for Second Point----|");


System.out.println("|
System.out.print("|Enetr x:-> ");
x2 = Integer.parseInt(br.readLine());
System.out.print("|Enetr y:-> ");

|");

Set-A

P a g e | 38
y2 = Integer.parseInt(br.readLine());
System.out.print("|Enetr z:-> ");
int z2 = Integer.parseInt(br.readLine());
System.out.println("|-----------------------------|");

ThreeDPoint Tdobj1 = new ThreeDPoint(x1,y1,z1);


ThreeDPoint Tdobj2 = new ThreeDPoint(x2,y2,z2);
dis = Tdobj1.Distance(Tdobj2);
System.out.printf("\n\tDistance between (%d,%d,%d) and (%d,%d,%d) is %.2f\n",x1,y2,z1,x2,y2,z2,dis);

}catch(Exception e){
System.out.println("\n\t"+e);
}
}}
Output:C:\Users\DEll\Java>java testCoordinate

Two Dimensional Distance Calculation


|---Input for First Point----|
|

|Enter x:-> 5
|Enter y:-> 10
|--------------------------------|
|---Input for Second Point----|
|
|Enter x:-> 15

Set-A

P a g e | 39

|Enter y:-> 10
|------------------------------------|

Distance between (5,10) and (15,10) is - 10.00

Three Dimensional Distance Calculation

|---Input for First Point----|


|

|Enter x:-> 1
|Enter y:-> 2
|Enter z:-> 3
|------------------------------|

|---Input for Second Point----|


|

|Enter x:-> 1
|Enter y:-> 3
|Enter z:-> 2
|-----------------------------------|

Distance between (1,3,3) and (1,3,2) is - 1.41

Set-A

P a g e | 40

Program to create an interface called Exam with a method (public)


percent_calc(). Create a class called Student with fields (private)
name, roll_no, mark1, mark2. And it has a parameterized constructor
and a public method display().Create another class Result which
inherits from Student and implements the interface Exam includes a
constructor. In this class define the method percent_calc() and call the
method display() by super keyword. Finally test your classes using a
driver class.

File Name: - testMultiple.java


Source code:import java.io.*;
interface Exam {
public void percent_calc();
}
class Student {
private String name;
private int roll_no, mark1,mark2;
Student(String name,int roll_no,int mark1,int mark2){
this.name = name;
this.roll_no = roll_no;
this.mark1 = mark1;
this.mark2 = mark2;
}
public int retMark1(){
return mark1;
}
public int retMark2(){
return mark2;
}

Set-A

P a g e | 41

public void Display(){


System.out.println("\n\t\t\tStudent Information");
System.out.println("\n Name: "+name);
System.out.println("\n Roll No: "+roll_no);
System.out.println("\n Mark 1: "+mark1);
System.out.println("\n Mark 2: "+mark2);
}
}
class Result extends Student implements Exam{
public Result(String name,int roll_no,int mark1,int mark2){
super(name,roll_no,mark1,mark2);
}

public void percent_calc(){


super.Display();
double num1,num2,res;

num1 = retMark1();
num2 = retMark2();
res = ((num1+num2)*100)/200;
System.out.println("\n\tPercentage = "+res);
}
}
class testMultiple {
public static void main(String args[]){
try{
Result obj = new Result("Ritesh Kumar",22,75,36);

Set-A

P a g e | 42
obj.percent_calc();

}catch(Exception e){
System.out.println("\n\t"+e);
}

}
}

Output:C:\Users\DEll\Java>java testMultiple
Student Information
Name: Ritesh Kumar
Roll No: 22
Mark 1: 75
Mark 2: 36
Percentage = 55.5

Set-A

P a g e | 43

An applet program to display the multiplication table from user choice

File Name: - multi.java


Source code:import java.io.*;
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;

/*
<applet code="multi" width=200 height=600>
</applet>
*/
public class multi extends Applet{
int res,table;
public void init(){
setBackground(Color.white);
setForeground(Color.black);
table = Integer.parseInt(JOptionPane.showInputDialog("Enter a Number"));
}
public void paint(Graphics g){
super.paint(g);

g.drawRect(1,1,197,540);
g.drawString(" The Multiplication table of "+table,20, 40);

Set-A

P a g e | 44

for(int i = 1;i<11;i++){
res = table*i;
g.drawString(table+" x "+i+" ="+res,60,50*i+25);
}
}
}
Output:-

Set-A

P a g e | 45

An applet program to take input for the date of birth of a person and
display the age in terms of years, months and days

File Name: - DOB.java


Source code:import java.io.*;
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.text.DateFormatSymbols;
import static java.util.Calendar.*;

/*
<applet code="DOB" width=268 height=50>
</applet>
*/
public class DOB extends Applet {
int res_month, res_year, res_date, date, month, year, x, flg=0;;
public void init(){
setBackground(Color.white);
setForeground(Color.black);
try{
date = Integer.parseInt(JOptionPane.showInputDialog("Enter Your date of
birth","Date Must be valid"));
month = Integer.parseInt(JOptionPane.showInputDialog("Enter Your month of
birth","Month Must be valid"));

Set-A

P a g e | 46

year = Integer.parseInt(JOptionPane.showInputDialog("Enter Your year of


birth","Year Must be valid"));
}catch(Exception e){
System.out.println("\n\t"+e);
System.exit(0);
}
GregorianCalendar birthdate = new GregorianCalendar(year, month-1,date);
GregorianCalendar today = new GregorianCalendar(); // Todays date

GregorianCalendar birthday = new


GregorianCalendar(today.get(YEAR),birthdate.get(MONTH),birthdate.get(DATE));

res_year = today.get(YEAR) - birthdate.get(YEAR);


res_month = today.get(MONTH) - birthdate.get(MONTH);
res_date = today.get(DATE) - birthdate.get(DATE);
x = birthdate.get(MONTH)+1;

if(res_month<=0)
{
if(res_year!=0)
{
res_year--;
res_month=12-res_month*(-1);
}
}
if(res_date<0)
{
if(res_month!=0)

Set-A

P a g e | 47
res_month--;
if(x==1||x==3||x==5||x==7||x==8||x==10||x==12)
res_date=31-res_date*(-1);
else if(birthdate.get(YEAR)%4==0&&x==2)
res_date=29-res_date*(-1);
else if(birthdate.get(YEAR)%4!=0&&x==2)
res_date=28-res_date*(-1);
else
res_date=30-res_date*(-1);
}

/* For Wrong Input Date*/


if(month>12||(month==2&&((year%4==0&&date>29)||(year%4!=0&&date>28))))
flg=1;
if(date>30&&(month==4||month==6||month==9||month==11||date>31))
flg=1;
if(year>today.get(YEAR))
flg=1;
if(year==today.get(YEAR) && month>today.get(MONTH)+1)
flg=1;
if(year==today.get(YEAR) && month==today.get(MONTH)+1&& date>today.get(DATE))
flg=1;

if(flg==1)
{
JOptionPane.showMessageDialog(null,"Invalid Date
!","Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);

Set-A

P a g e | 48
}

}
public void paint(Graphics g){
super.paint(g);

g.drawRect(1,1,260,47);
g.drawString("You are "+res_year+" years, "+res_month+" months, "+res_date+"
days old.",20, 40);

}
}

Output:C:\Users\DEll\Java>appletviewer DOB.java

Set-A

P a g e | 49

A program to demonstrate that as a high-priority thread executes, it


will delay the execution of all lower-priority threads

File Name: - HeighPriority.java


Source code:import java.io.*;
class HeighPriority extends Thread{
public void run(){
Thread t = Thread.currentThread();
System.out.println("\nThread Name: "+t.getName()+", Thread Priority: "+t.getPriority());

}
public static void main(String args[]){
HeighPriority thread1 = new HeighPriority();
HeighPriority thread2 = new HeighPriority();
HeighPriority thread3 = new HeighPriority();
HeighPriority thread4 = new HeighPriority();
HeighPriority thread5 = new HeighPriority();

thread1.setName("Higher Thread-1");
thread2.setName("Higher Thread-2");
thread3.setName("Lower Thread-1");
thread4.setName("Lower Thread-2");
thread5.setName("Lower Thread-3");

thread1.setPriority(10);
thread2.setPriority(9);
thread3.setPriority(3);

Set-A

P a g e | 50
thread4.setPriority(2);
thread5.setPriority(1);

System.out.println("Thread 5 started");
thread5.start();
System.out.println("Thread 4 started");
thread4.start();
System.out.println("Thread 1 started");
thread1.start();
System.out.println("Thread 2 started");
thread2.start();
System.out.println("Thread 3 started");
thread3.start();
}
}
Output:C:\Users\DEll\Java>java HeighPriority
Thread 5 started
Thread 4 started
Thread 1 started
Thread Name: Lower Thread-3, Thread Priority: 1
Thread Name: Higher Thread-1, Thread Priority: 10
Thread 2 started
Thread Name: Lower Thread-2, Thread Priority: 2
Thread Name: Higher Thread-2, Thread Priority: 9
Thread 3 started
Thread Name: Lower Thread-1, Thread Priority: 3

You might also like