Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Programming With Java-102040403

PRACTICAL – 1
Basic Program

1. Study of the class path and java runtime environment

There are two ways of set a path variable


1) By ordinary method
2) By command prompt
By Ordinary Method
Step 1: Open an Environment Variables Dialog box by searchthe box

Step 2: Click on New Button -> Enter PATH as a variable name and copy the

path of the bin file of JDK andpaste to the variable value ->

click on OK.

By Command Prompt
Syntax: path [[<drive>:]<path>[;...][;%PATH%]]

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

Code:
public class Demo {

public static void main(String[] args){

System.out.println("Hello World!");
}
}

Output:

P02: Write a program to


• Implement command line calculator
• To prints Fibonacci series.

Code:
import java.util.*;
public class First_2
{
public static void main (String s[])
{

float a,b;
Scanner ob = new Scanner(System.in);
int select = 1;

System.out.println("Here\n!!You have two choice!!\n->1.Use Calculator and perform


operation\n->2.Prints Fibonacci series:");
int ch = ob.nextInt();
switch(ch)
{
case 1 :
do{
System.out.println("Enter the value of a and b : ");

a = ob.nextFloat();
// Scanner ob1 = new Scanner(System.in);
b = ob.nextFloat();

System.out.println("Here\n1. '+' Addition\n2. '-' Subtraction\n3. '*' Multiplication\n4. '/'


Division \n5. '%' Modulus \n0. exit ");
select = ob.nextInt();

switch(select)
{
case 1 :
{
System.out.println("Addition :"+a+" + "+b+" = "+(a+b));
}
break;

case 2 :
{
System.out.println("Subtraction :"+a+" - "+b+" = "+(a-b));
}

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

break;

case 3 :
{
System.out.println("Multiplication :"+a+" * "+b+" = "+(a*b));
}
break;

case 4 :
{
System.out.println("Division :"+a+" / "+b+" = "+(a/b));
}
break;

case 5 :
{
System.out.println("Modulus :"+a+" % "+b+" = "+(a%b));
}
break;

case 0 :
{
System.out.println("!!!Thank you!!!");
}
break;

default :
break;
}
} while(select!=0);
break;

case 2 :
{
System.out.println("How many elements you want to print in the fibonacci series :");
int ele = ob.nextInt();
int t1=0,t2=1;
int next = t1+t2;
System.out.print(""+t1+" "+t2);
for(int i=3;i<=ele;i++)
{
System.out.print(" "+next);
t1=t2;
t2=next;
next=t1+t2;
}

}
break ;
}

}
}

Output :

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

PRACTICAL – 2
Array:

1. Define a class Array with following member

Field:
int data[];
Function:
Array( ) //create array data of size 10
Array(int size) // create array of size size
Array(int data[]) // initialize array with parameter array
void Reverse _an _array () //reverse element of an array
int Maximum _of _array () // find maximum element of array
int Average_of _array() //find average of element of array
void Sorting () //sort element of array
void display() //display element of array
int search(int no) //search element and return index else return -1
int size(); //return size of an array
Use all the function in main method. Create different objects with different
constructors.
Code :

import java.util.*;
class Array{
int data[];
int size;
Array()
{
size =5;
data = new int[size];
}
Array(int s)
{
size = s;
data = new int [size];
}
public void Read()
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter array elements :");
for(int i=0;i<data.length;i++)
{
data[i]=obj.nextInt();
}

}
public void Display()

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

{
System.out.println("Array elements :");
for(int i = 0; i<data.length;i++)
{
System.out.println(""+(i+1)+":"+data[i]);
}
}
public void Rev_array()
{
System.out.println("Reverse Array elements :");
// for(int i = data.length-1; i>-1;i--)
// {
// System.out.println(""+(i+1)+":"+data[i]);
// }
for(int i =0;i<data.length/2;i++)
{
int t;
t= data[i];
data[i]=data[data.length-1-i];
data[data.length-1-i]=t;
}
Display();
}
public int Max()
{
int max=data[0];
for( int i=0;i<data.length;i++)
{
if(data[i]>max)
{
max=data[i];
}
}
return max;
}
public float Avg_array()
{
int sum = 0;
for(int i =0;i<data.length;i++)
{
sum = sum + data[i];
}
float avg = (float)sum/data.length;
return avg;
}
public void sort_array()
{
int temp;

for(int i=0;i<data.length-1;i++)
{
for(int j= i+1;j<data.length;j++)
{
if(data[j]<data[i])
{

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

temp= data[i];
data[i] = data[j];
data[j]=temp;

}
}
}
System.out.println("Sorted ->");
Display();
}
public int Search_element()
{
int search,found=0;
Scanner obj = new Scanner(System.in);
System.out.println("Enter array elements Which you want to find:");
search=obj.nextInt();

for(int i=0;i<data.length;i++)
{
if(search==data[i])
{
found=1;
break;
}
}
if(found==1)
{
System.out.println("!!!--->Element is founded<---!!!");
}
else{
System.out.println("!!!--->Element is not founded<---!!!");
}

return 1;

}
}
class Demo
{
public static void main(String s[])
{
int size;

System.out.print("Enter the arrary size :");


Scanner ob = new Scanner(System.in);
size = ob.nextInt();
Array a1 = new Array(size);

// Array a2 = new Array(10);


a1.Read();
a1.Display();
int max = a1.Max();
System.out.println("Max element is :"+max);
a1. Rev_array();

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

float avg = a1.Avg_array();


System.out.println("Average of array is :"+avg);

a1.sort_array();

int search = a1.Search_element();


// System.out.println(+search);
}
}
Output:

2. Define a class Matrix with following.

Field:
int row, column;
float mat[][]
Function:

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

Matrix(int a[][])
Matrix()
Matrix(int rwo, int col)
void readMatrix() //read element of array
float [][] transpose( ) //find transpose of first matrix
float [][] matrixMultiplication(Matrix second ) //multiply two matrices and
return result
void displayMatrix(float [][]a) //display content of argument array
void displayMatrix() //display content
float maximum_of_array() // return maximum element of first array
float average_of_array( ) // return average of first array
create three object of Matrix class with different constructors in main and
test all the functions in main*/

Code :

import java.util.Scanner;
class Matrix
{
int row,column;
float mat[][];
Matrix()
{
row=3;
column=3;
mat=new float[row][column];
}
Matrix(float a[][])
{
column=a[0].length;
row=a.length;
mat=new float[row][column];
mat=a;
}
Matrix(int row,int column)
{
this.row=row;
this.column=column;
mat=new float[row][column];
}
public void read()
{
int i,j;
Scanner sc=new Scanner(System.in);
System.out.println("=> Enter the element for "+row+"*"+column);
for(i=0; i<row; i++)
{

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

for(j=0; j<column; j++)


{
mat[i][j]= sc.nextFloat();
}
}
System.out.println("-----------------------------");
}
public void display()
{
System.out.println("-----------------------------");
System.out.println("Our matrix are...");
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{
System.out.print(mat[i][j] +" ");
}
System.out.printf("\n");
}
}
public void display(float a[][])
{
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{
System.out.print(a[i][j] +" ");
}
System.out.printf("\n");
}
}
public float max()
{
float max=0;
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{
if(mat[i][j]>max)
max=mat[i][j];
}
}
return max;
}
public float avg()
{
float sum=0,avg;
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

{
sum=sum+mat[i][j];
}
}
avg=(sum)/(row*column);
return avg;
}
public float[][] transmatrix()
{
float trans[][];
trans=new float[row][column];
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{

}
}
return trans;
}
public float[][] matmul(Matrix second)
{
float mul[][];
mul=new float[row][second.column];
for(int i=0;i<row;i++)
{
for(int j=0;j<second.column;j++)
{
mul[i][j]=0;
for(int k=0;k<second.row;k++)
{
mul[i][j]+=mat[i][k]*mat[k][j];
}
}
}
return mul;
}
}
public class MatDemo
{
public static void main(String[] args)
{
Matrix m1=new Matrix();
m1.display();
float a[][] = {{1,2,3},{4,5,6},{7,8,9}};
Matrix m3=new Matrix(a);
m3.display();
Matrix m2=new Matrix(3,3);
Matrix m5=new Matrix(3,3);
System.out.println("Enter first matrix by user....");

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

m2.read();
m2.display();
System.out.println("Maximum element is"+m2.max());
System.out.println("average of element is "+m2.avg());
System.out.println("Transpose of Matrix are...");
float b[][]=m2.transmatrix();
m2.display(b);
System.out.println("Enter second matrix....");
m5.read();
m5.display();
System.out.println("Now multiplication of matrix table is .....");
float c[][]=m2.matmul(m5);
m3.display(c);
}
}
Output:

3.Write a program to demonstrate usage of different methods of Wrapper class


Code :

public class Wrapper


{
public static void main(String[] args) throws Exception
{
System.out.println("Using valueOf() method to create an object of a Wrapper class from a String
passed into it ");
Integer a = Integer.valueOf("100");
System.out.println("a: " + a);

System.out.println("Using parseDataType() method to convert a given String to primitive type");


String s = "11";
int b = Integer.parseInt(s);

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

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

System.out.println("Using toString() method to convert a Wrapper class type object into a String.
");
Double d = 11.22;
String t = d.toString();
System.out.println("t: " + t);
}
}

Output:

4. Write a program to demonstrate usage of String and StringBuffer class.

Code :

class string
{
public static void main(String[] args) throws Exception
{
System.out.println("Printing String a ");
String a = "Hello, String is immutable";
System.out.println(a);
System.out.println( "\nWhen changes are made in a String object, they do not get updated in same
string, and rather a new object is created with new changes. ");
System.out.print("\nNew String object created with changes: ");

System.out.println(a.replace('H', 'B'));
System.out.println( "\nOlder String a still remains the same as before as Strings are immutable in
JAVA. Printing String a");
System.out.println(a);

System.out.println("\nCreating a StringBuffer which provides modification functionalities. ");


StringBuffer sb = new StringBuffer("I am a StringBuffer");
System.out.print("\nStringBuffer sb: " + sb);

sb.append(", I am mutable");
System.out.println("\nsb after updation: " + sb);

sb.reverse();
System.out.println("Reversing sb: " + sb);
}
}

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

Output:

5. Define a class Cipher with following data Field: String plainText; int key
Functions: Cipher(String plaintext,int key) String Encryption( ) String
Decryption( ) Read string and key from command prompt and replace every
character of string with character which is key place down from current
character. Example plainText = “GCET” Key = 3 Encryption function written
following String “ JFHW” Decryption function will convert encrypted string to
original form “GCET”

Code :

import java.util.*;
class Cipher
{
String plaintext;
int key;
Cipher(String plaintext, int key)
{
this.plaintext=plaintext;
this.key=key;
}
String Encryption()
{
char x[]=plaintext.toCharArray();
for(int i=0;i<x.length;i++)
{
x[i]=(char)((int)x[i]+key);
}
this.plaintext=new String(x);
return new String(x);
}
String Decryption()
{
char x[]=plaintext.toCharArray();
for(int i=0;i<x.length;i++)
{

12102130501074 – VISHNU MAKUPALLI


Programming With Java-102040403

x[i]=(char)((int)x[i]-key);
}
return new String(x);
}
}
class CipherDemo
{
public static void main(String[] args)
{
String s;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
s=sc.next();
Cipher c=new Cipher(s,3);
System.out.println("Encrypton is : "+c.Encryption());
System.out.println("Decryption is : "+c.Decryption());
}
}

Output:

12102130501074 – VISHNU MAKUPALLI


[Document title]

PRACTICAL 3:
1. Create a class BankAccount that has Depositor name , Acc_no,
Acc_type, Balance as Data Members and void createAcc() . void
Deposit(), void withdraw() and void BalanceInquiry as Member
Function. When a new Account is created assign next serial no as
account number. Account number starts from 1

CODE:
import java.util.Scanner;
class BankAccount
{
public Scanner sc = new Scanner(System.in);
String aname;
int acc_no;
static int acc_no_gen=0;
String acc_type;
int bal=0,withdraw=0;
int dep=0;

BankAccount()
{
int ch;
acc_no=++acc_no_gen;
System.out.println("A new Account Created With Account Number "+acc_no);

System.out.println("\nEnter account holder's name::");


aname=sc.nextLine();

System.out.println("\nEnter \n1)Savings Account\n2)Business Account");


ch=sc.nextInt();

if(ch==1)
{
acc_type="Savings";
System.out.println("\nSAVINGS ACCOUNT CREATED\n");

}
else if(ch==2)
{
acc_type="Business";
System.out.println("BUSINESS ACCOUNT CREATED");

}
else{
System.out.println("INVLAID INPUT");

Varesh Patel:-12102130501071
[Document title]

void Deposite(int my_acc_no)


{
System.out.println("\nEnter the amout to be deposited::\n");
dep = sc.nextInt();
bal=bal+dep;
}

void Withdraw(int my_acc_no)


{
System.out.println("\nEnter the amout to be withdrawn::\n");
withdraw = sc.nextInt();
if(bal>withdraw){
bal=bal-withdraw;
}
else{
System.out.println("INSUFFICIENT BALANCE\n");
}
}

void Bal_inquiry(int my_acc_no)


{

System.out.println("\n==================================================\
n");
System.out.println("\nBalance in Account is::"+bal);
}

void acc_inquiry(int my_acc_no)


{

System.out.println("\n==================================================\
n");
System.out.println("\nAccount Holder's name::"+aname);
System.out.println("\nAccount Number is::"+acc_no);
System.out.println("\nAccount Type is::"+acc_type);
System.out.println("\nBalance in Accountis::"+bal);

System.out.println("\n==================================================\
n");
}

Varesh Patel:-12102130501071
[Document title]

class demo
{
public static void main(String args[])
{
BankAccount ac1 = new BankAccount();
BankAccount ac2 = new BankAccount();
/*ac1.Bal_inquiry(ac1.acc_no);
ac1.Withdraw(ac1.acc_no);*/
ac1.Deposite(ac1.acc_no);
//ac1.Bal_inquiry(ac1.acc_no);
ac1.acc_inquiry(ac1.acc_no);
ac2.Deposite(ac2.acc_no);
ac2.acc_inquiry(ac2.acc_no);
ac1.acc_inquiry(ac1.acc_no);

Varesh Patel:-12102130501071
[Document title]

Varesh Patel:-12102130501071
[Document title]

2. Create a class time that has hour, minute and second as


data
members. Create a parameterized constructor to initialize Time
Objects. Create a member Function Time Sum (Time, Time) to
sum two time objects.

CODE:
import java.util.Scanner;
class Time
{ int hour,minutes,sec;
Time(int a , int b , int c)
{ hour = a;
minutes = b;
sec = c;
}
Time Sum(Time a, Time b)
{ int h,m,s;
h = a.hour + b.hour;
m = a.minutes + b.minutes;
s = a.sec + b.sec;
if(s >= 60)
{
m = m + (s / 60);
s = s % 60;
}
else if(m >= 60)

Varesh Patel:-12102130501071
[Document title]

{
h = h + (m / 60);
m = m % 60;
}
hour = h;
minutes = m;
sec = s;
return this;
}
}
class Clock
{
public static void main(String args[])
{
Time T1 = new Time(2,32,45);
Time T2 = new Time(1,25,41);
Time T3 = new Time(0,0,0);
Time T4=T3.Sum(T1,T2);
System.out.println("time : "+T4.hour+" : "+T4.minutes+" : "+T4.sec);
}
}

OUTPUT:

3. Define a class with the Name, Basic salary and dearness


allowance as data members. Calculate and print the
Name, Basic salary(yearly), dearness allowance and tax
deduced at source(TDS) and net salary, where TDS is
charged on gross salary which is basic salary + dearness
allowance and TDS rate is as per following table. DA is
74% of Basic Salary for all. Use appropriate member
function.

CODE:
import java.util.Scanner;

Varesh Patel:-12102130501071
[Document title]

class Bank{
Scanner inp=new Scanner(System.in);

String Name;
double Basic_Salary;
double Dr_allowance;
double Gross_Salary;
double Net_Sal;

void setdata(){
System.out.print("\nEnter Name: ");
Name=inp.nextLine();
System.out.print("\nEnter Basic Salary: ");
Basic_Salary=inp.nextDouble();

void Calculate(){
double Tds;
Dr_allowance=Basic_Salary*0.74;
System.out.print("\nDearness Alowance: "+Dr_allowance);
Gross_Salary=Basic_Salary+Dr_allowance;
System.out.print("\nGross Salary= "+Gross_Salary);
if(Gross_Salary<100000){
Tds=0;
System.out.print("\nNet Salary="+Gross_Salary);
}
else{
if(Gross_Salary>100000){
Tds=Gross_Salary*0.1;
System.out.print("\nTDS= "+Tds);
Net_Sal=Gross_Salary-Tds;
}
}

void display(){
System.out.print("\nName="+Name);
System.out.print("\nBasic Salary(Yearly)= "+Basic_Salary);
System.out.print("\nDearness Allowance(DA)= "+Dr_allowance);

System.out.print("\nGross Salary= "+Gross_Salary);


System.out.print("\nNet Salary= "+Net_Sal);
}
}

class Demo{
public static void main(String args[]){
Bank ob=new Bank();

Varesh Patel:-12102130501071
[Document title]

ob.setdata();
ob.Calculate();
ob.display();
}
}

Output:

Varesh Patel:-12102130501071
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

Practical-4
4.1: class Cricket having data members name, age and member
methods display() and
setdata(). class Match inherits Cricket and has data members
no_of_odi, no_of_test.
Create an array of 5 objects of class Match. Provide all the
required data through
the command line and display the information.

CODE;
class Cricket {
String Name;
int Age;

void setdata(String nm, int ag) {


this.Name = nm;
this.Age = ag;
}

void display() {
System.out.print("\nPlayer Name: " + this.Name);
System.out.print("\nPlayer Age: " + this.Age);
}
}

class Match extends Cricket {


int no_of_odi, no_of_test;

void getdata(int o, int t) {


this.no_of_odi = o;
this.no_of_test = t;
}

void display() {
super.display();
System.out.println("\nNo. of Odi matches played: " + this.no_of_odi);
System.out.println("No. of Test matches played: " + this.no_of_test);
}
}

// Varesh 20 13 34 Harsh 20 23 45 Viraj 18 23 54 Vishnu 69 23 1 Kirti 98 4 4


24
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
class command {
public static void main(String args[]) {
Match arr[];
arr = new Match[5];
int count = 0, i = 0;

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


arr[k] = new Match();

for (int j = 0; j < args.length; j += 4) {


arr[i].setdata(args[count++], Integer.parseInt(args[count++]));
arr[i].getdata(Integer.parseInt(args[count++]), Integer.parseInt(args[count++]));
i++;
}

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


arr[j].display();
}
}
}

25
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

4.2: Define a class Cripher with following data


Field:
String plainText;
int key
Functions:
Cipher(String plaintext,int key)
abstract String Encryption( )
abstract String Decryption( )
Derived two classes Substitution_Cipher and Caesar_Cipher
override
Encryption() and Decryption() Method. in substitute cipher every
character of
string is replaced with another character. For example, In this
method you will
replace the letters using the following scheme.
Plain Text: a b c d e f g h i j k l m n o p q r s t u v w x y z
Cipher Text: q a z w s x e d c r f v t g b y h n u j m i k o l p
So if string consist of letter “gcet” then encrypted string will be
”ezsj” and decrypt
it to get original string
In ceaser cipher encrypt the string same as program 5 of LAB 5.
CODE;
import java.util.Scanner;
abstract class cipher{
String plain_text;
cipher(String a){
this.plain_text=a;
}
abstract public String encryption();
abstract public String decryption();
}
class Substitution_Cipher extends cipher{
Substitution_Cipher(String a){
super(a);
}
26
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
public String encryption(){
char a[]=plain_text.toCharArray();
int i;
for(i=0;i<a.length;i++){
String plain="a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N
O P Q R S T U V W X Y Z";
String encrypt="q a z w s x e d c r f v t g b y h n u j m i k o l p Q A Z W X E D C R F V T
G B Y H N U J M I K O L P";
int d=plain.indexOf(a[i]);
char ch=encrypt.charAt(d);
a[i]=ch;
}
this.plain_text=new String(a);
return new String(a);
}
public String decryption(){
char a[]=plain_text.toCharArray();
int i;
for(i=0;i<a.length;i++){
String encrypt="q a z w s x e d c r f v t g b y h n u j m i k o l p Q A Z W X E D C R F V T
G B Y H N U J M I K O L P";
String plain="a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N
O P Q R S T U V W X Y Z";
int d=encrypt.indexOf(a[i]);
char ch=plain.charAt(d);
a[i]=ch;
}
this.plain_text=new String(a);
return new String(a);
}
}
class Caeser_Cipher extends cipher{
int ar;
Caeser_Cipher(String a, int ar){
super(a);
this.ar=ar;
}
public String encryption(){
char c[]=plain_text.toCharArray();
int i;
for(i=0;i<c.length;i++){
c[i]=(char)((int)c[i]+ar);
}
this.plain_text=new String(c);
return new String(c);
}
public String decryption(){
//return " ";
char c[]=plain_text.toCharArray();
int i;
27
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
for(i=0;i<c.length;i++){
c[i]=(char)((int)c[i]-ar);
}
this.plain_text=new String(c);
return new String(c);
}
}
class encrypt {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name,Varesh;
System.out.println("Enter a text that is to be encrypted");
name=sc.next();
Substitution_Cipher s=new Substitution_Cipher(name);
System.out.println("Your encrypted text is: "+s.encryption());
System.out.println("Your decrypeted text is: "+s.decryption());
int a;
System.out.println("Enter a key for encryption");
a=sc.nextInt();
Caeser_Cipher csd=new Caeser_Cipher(name, a);
System.out.println("Your encrypted text is: "+csd.encryption());
System.out.println("Your decrypted text is: "+csd.decryption());
}
}

4.3: Declare an interface called Property containing a method


computePrice to compute
and return the price. The interface is to be implemented by
following two classes i)
Bungalow and ii) Flat.
Both the classes have following data members
- name
- constructionArea

28
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

The class Bungalow has an additional data member called


landArea. Define
computePrice for both classes for computing total price. Use
following rules for
computing total price by summing up sub-costs:
Construction cost(for both classes):Rs.500/- per sq.feet Additional
cost ( for Flat) : Rs. 200000/- ( for Bungalow ): Rs. 200/- per sq.
feet for landArea Land cost ( only for Bungalow ): Rs. 400/- per
sq. feet Define method main to show usage of method
computePrice.
CODE;
import java.util.Scanner;
interface property{
public double Compute_property(double d);
}
class Bungalow implements property{
String name;
String Construction_area;
double landarea;
Bungalow(String a, String b,double c){
this.name=a;
this.Construction_area=b;
this.landarea =c;
System.out.println("Construction Name: "+name+"\n Construction Area:
"+Construction_area);
System.out.println("Your construction cost is: "+(c*500));
System.out.println("The cost of the landarea: "+(c*200));
System.out.println("The land cost: "+(c*400));
}
public double Compute_property(double d){
this.landarea=d;
return (d*500)+(d*200)+(d*400);
}
}
class flat implements property{
String name;
String Construction_area;
double land;
flat(String a, String b, double s){
this.name=a;
this.Construction_area=b;
this.land=s;
System.out.println("Construction Name: "+name+"\n Construction Area:
"+Construction_area);
System.out.println("Your construction cost is: "+(s*500));
}
29
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
public double Compute_property(double d){
this.land=d;
return (d*500)+200000;
}
}
public class interfaces {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name;
String area;
double persq;
int choice;
System.out.println("What is the type of your house.....");
System.out.println("1.Bungalow");
System.out.println("2.Flat");
choice=sc.nextInt();
System.out.println("------------------------------------------------------------------------------");
switch(choice){
case 1:{
System.out.println("Enter your name or your house name");
name=sc.next();
System.out.println("Enter the area in which your house is located");
area=sc.next();
// sc.close();
System.out.println("Enter the square feeet area of your house");
persq=sc.nextDouble();
System.out.println("----------------------------------------------------------------------------
--");
Bungalow b= new Bungalow(name,area, persq);
System.out.println("----------------------------------------------------------------------------
--");
System.out.println("After adding following costs: \nConstruction cost: Rs.500/- per
sq.feet\nAdditional cost: Rs. 200/- per sq.feet for landArea\nLand cost: Rs. 400/- per sq.
feet");
System.out.println("----------------------------------------------------------------------------
--");
System.out.println("Your total cost is: "+b.Compute_property(persq));
break;
}
case 2:{
System.out.println("Enter your name or your house name");
name=sc.next();
System.out.println("Enter the area in which your house is located");
area=sc.next();
// sc.close();
System.out.println("Enter the square feeet area of your house");
persq=sc.nextDouble();
System.out.println("----------------------------------------------------------------------------
--");
flat f=new flat(name,area, persq);
30
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
System.out.println("----------------------------------------------------------------------------
--");
System.out.println("After adding following cost:\nConstruction cost: Rs.500/- per
sq.feet\nAdditional cost: Rs.200000");
System.out.println("---------------------------------------------------------------------------
---");
System.out.println("Your total cost is: "+f.Compute_property(persq));
break;
}
}
}
}

4.4: Define following classes and interfaces.


public interface GeometricShape {
public void describe();
}
public interface TwoDShape extends GeometricShape {
public double area();
}
public interface ThreeDShape extends GeometricShape {
public double volume();
}
public class Cone implements ThreeDShape {
private double radius;
31
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

private double height;


public Cone (double radius, double height)
public double volume()
public void describe()
}
public class Rectangle implements TwoDShape {
private double width, height;
public Rectangle (double width, double height)
public double area()
public double perimeter()
public void describe()
}
public class Sphere implements ThreeDShape {
private double radius;
public Sphere (double radius)
public double volume()
public void describe()
}
Define test class to call various methods of Geometric Shape.
CODE;
interface Geometric_shape{
public void describe();
}
interface TwoDshape extends Geometric_shape{
public double area();
}
interface ThreeDshape extends Geometric_shape{
public double volume();
}
class cone implements ThreeDshape{
private double r;
private double h;
cone(double r, double h){
this.r=r;
this.h=h;
}
public double volume(){
return (3.14*r*r*h)/3;
}
public void describe(){
System.out.println("The shape is Cone.");

}
32
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
}
class rectangle implements TwoDshape{
private double w;
private double h;
rectangle(double w, double h){
this.w=w;
this.h=h;
}
public void describe(){
System.out.println("The shape is Rectangle.");
}
public double area(){
return w*h;
}
public double parameter(){
return (w+h)*2;
}
}
class sphere implements ThreeDshape{
private double r;
sphere(double r){
this.r=r;
}
public void describe(){
System.out.println("The shape is sphere.");
}
public double volume(){
return (4*(3.14*r*r*r))/3;
}
}
class test extends sphere implements ThreeDshape,TwoDshape{
private double w;
private double h;
private double r;
test(double w, double r, double h){
super(r);
this.w=w;
this.h=h;
this.r=r;
}
public void describe(){
System.out.println("SHAPE : sphere");
}
public double area(){
return 4*(3.14*r*r);
}
public double volume(){
return (4*(3.14*r*r*r))/3;

}
33
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

}
public class shape {
public static void main(String[] args) {
System.out.println("---------------------------------------------");
cone c=new cone(2,2);
c.describe();
System.out.println("The volume of the cone is: "+c.volume());
System.out.println("---------------------------------------------");
rectangle r=new rectangle(2, 3);
r.describe();
System.out.println("The area of the rectangle is: "+r.area());
System.out.println("The parameter of the rectangle is: "+r.parameter());
System.out.println("---------------------------------------------");
sphere s=new sphere(5);
s.describe();;
System.out.println("The volume of the sphere is: "+s.volume());
System.out.println("---------------------------------------------");
test t=new test(2, 2, 2);
t.area();
t.describe();;
t.volume();
System.out.println("The area of the sphere is: "+t.area());
System.out.println("The volume of the sphere is: "+t.volume());
System.out.println("---------------------------------------------");

}
}

34
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

Practical-5
5.1: Define two nested classes: Processor and RAM inside the
outer class: CPU with following
data members
class CPU {
double price;
class Processor{ // nested class
double cores;
double catch()
String manufacturer;

double getCache()
void displayProcesorDetail()
}
protected class RAM{ // nested protected class
// members of protected nested class
double memory;
String manufacturer;
Double clockSpeed;
double getClockSpeed()
void displayRAMDetail()
}
}
1. Write appropriate Constructor and create instance of Outer
and inner class and call
the methods in main function
CODE;
import java.util.Scanner;
public class cpu {
//Write appropriate Constructor and create instance of Outer and inner class and call
//the methods in main function
Scanner sc=new Scanner(System.in);
double price;
class procesor{

35
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

double cores;
double catche;
String manufacturer;
procesor(String s, double cores){
this.cores=cores;
this.manufacturer=s;
}
double getcatch(){
System.out.println("How many cathe do you want?");
double d=sc.nextDouble();
return d;
}
void display_processor_details(){
System.out.println("catche: "+getcatch());
System.out.println("Manufacturer: "+manufacturer);
System.out.println("Cores: "+cores);
}
}
class Ram{
double memory;
String manufacturer;
double clockspeed;
Ram(String s, double cores){
this.memory=cores;
this.manufacturer=s; }
double clockspeed(){
System.out.println("How much clockspeed you want?");
double cs=sc.nextDouble();
return cs;}
void display_Ram_details(){
System.out.println("clockspeed: "+clockspeed());
System.out.println("Manufacturer: "+manufacturer);
System.out.println("memory: "+memory);
}
}

public static void main(String[] args) {


cpu c=new cpu();
cpu.procesor p=c.new procesor("Intel", 9);
//cpu c=new cpu();
cpu.Ram r=c.new Ram("ASUS", 10000);
p.display_processor_details();
r.display_Ram_details();
}
}

36
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

5.2: . Write a program to demonstrate usage of static inner class,


local inner class and
anonymous inner class
CODE;
class inner{
//static innerclass
private static String message="This is static inner class";
public static class sinner{
void print(){
System.out.println(message);
}
}
//Local inner class
int outer=100;
void test(){
Inner in=new Inner();
in.display();
}
class Inner{
void display(){
System.out.println("This is local inner class");
System.out.println(" outer: "+outer);

}
}
//Anonymous inner class
interface age{
int age=19;
public void getage();
}
public static void main(String[] args) {
inner i=new inner();
i.test();
age a=new age(){

37
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD

public void getage(){


System.out.println("This is annonymous inner class");
System.out.println("Age: "+age);
}
};
a.getage();
//creating instance of static inner class
inner.sinner s=new inner.sinner();
s.print();
}
}

38
Programming in Java: 102044502
102044502 | Programming with Java

Practical-6
1. Declare a class InvoiceDetail which accepts a type parameter which is of type
Number with following data members class InvoiceDetail { private String
invoiceName; private N amount; private N Discount // write getters, setters and
constructors } Call the methods in Main class .

Code:
import java.util.*;

class InvoiceDetail<N extends Number>


{
private String invoiceName;
private N amount;
private N Discount;

InvoiceDetail() {
}

InvoiceDetail(String in, N amt, N d)


{
this.invoiceName = in;
this.amount = amt;
this.Discount = d;
}

public String getInvoiceName()


{
return invoiceName;
}

public void setInvoiceName(String invoiceName)


{
this.invoiceName = invoiceName;
}

public N getAmount()
{
return amount;
}

public void setAmount(N amount)


{
this.amount = amount;
}

public N getDiscount()

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

{
return Discount;
}

public void setDiscount(N discount)


{
Discount = discount;
}
}

class ExecuteInvoiceDetails
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String INVOICE_NAME;
double DISCOUNT, AMOUNT;

System.out.println(" USING CONSTRUCTOR");


System.out.println();
InvoiceDetail<Number> ob2 = new InvoiceDetail<>("Pillow", 700, 20);
System.out.println(" Details of Second Invoice: ");
System.out.println(" Invoice Name: " + ob2.getInvoiceName());
System.out.println(" Amount: " + ob2.getAmount());
System.out.println(" Discount: " + ob2.getDiscount());

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

InvoiceDetail<Number> ob1 = new InvoiceDetail<>();


System.out.println(" USING GETTERS AND SETTERS");
System.out.println();
System.out.print(" Enter Invoice Name: ");
INVOICE_NAME = sc.nextLine();
System.out.print(" Enter Product Price: ");
AMOUNT = sc.nextDouble();
System.out.print(" Enter Discount to Apply: ");
DISCOUNT = sc.nextDouble();

ob1.setInvoiceName(INVOICE_NAME);
ob1.setAmount(AMOUNT);
ob1.setDiscount(DISCOUNT);
System.out.println();
System.out.println(" Details of First Invoice: ");
System.out.println(" Invoice Name: " + ob1.getInvoiceName());
System.out.println(" Amount: " + ob1.getAmount());
System.out.println(" Discount: " + ob1.getDiscount());
sc.close();
}
}

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Output:

2. Implement Generic Stack

Code:
import java.util.ArrayList;

class Stack<T>
{
ArrayList<T> st;
T st1;
int size;
int TOP = -1;

Stack(int size)
{
this.size = size;
this.st = new ArrayList<T>(size);
}

void push(T value)


{
if (isFull())
{
System.out.println("Overflow");
return;
}
if (st.size() > ++TOP)
st.set(TOP, value);
else
st.add(value);
System.out.println("Value Pushed");

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

T pop()
{
if (isEmpty())
{
System.out.println("Undeflow");
return null;
}
return st.get(TOP--);
}

T peep()
{
if (isEmpty())
{
System.out.println("Undeflow");
return null;
}
return st.get(TOP);
}

void display()
{
if (isEmpty())
{
System.out.println("Underflow");
return;
}
System.out.println("Stack is: ");
for (int i = TOP; i >= 0; i--)
{
System.out.println(" " + st.get(i));
}
}

Boolean isFull()
{
return TOP >= size;
}

Boolean isEmpty()
{
return TOP < 0;
}
}

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

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Stack<Integer> IntStack = new Stack<>(4);


IntStack.push(12);
IntStack.push(20);
IntStack.push(11);
System.out.println("\nPopped Value: " + IntStack.pop());
System.out.println("Top Value: " + IntStack.peep());
IntStack.display();

System.out.println();

Stack<Character> CharStack = new Stack<>(5);


CharStack.push('J');
CharStack.push('a');
CharStack.push('v');
CharStack.push('a');
System.out.println("\nPopped Value: " + CharStack.pop());
System.out.println("Top Value: " + CharStack.peep());
CharStack.display();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

3. Write a program to sort the object of Book class using comparable and
comparator interface. (Book class consist of book id, title, author and publisher
as data members)

Code:
import java.util.Comparator;

class Book implements Comparable<Book>, Comparator<Book>


{
private String BOOK_NAME;

Book(String bn)
{
this.BOOK_NAME = bn;
}

String getBookName()
{
return BOOK_NAME;
}

public int compareTo(Book o)


{
if (this.BOOK_NAME == o.getBookName())
{
return 1;
}
return 0;
}

public int compare(Book o1, Book o2)


{
if (o1.getBookName() == o2.getBookName())
{
return 1;
}
return 0;
}

class ExecuteBook
{
public static void main(String[] args)
{
Book ob1 = new Book("Java"),
ob2 = new Book("Python"),
ob3 = new Book("Java");

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

System.out.println(" Names of Books are: " + ob1.getBookName() + ", " +


ob2.getBookName() + " & " + ob3.getBookName());
System.out.println();

System.out.println(" Comparing Books using Comparator: ");


if (ob1.compare(ob2, ob3) == 1)
{
System.out.println(ob2.getBookName() + " = " + ob3.getBookName());
} else
{
System.out.println(ob2.getBookName() + " != " + ob3.getBookName());
}
System.out.println();
if (ob2.compare(ob1, ob3) == 1)
{
System.out.println(ob1.getBookName() + " = " + ob3.getBookName());
} else
{
System.out.println(ob1.getBookName() + " != " + ob3.getBookName());
}
System.out.println();
if (ob3.compare(ob2, ob1) == 1)
{
System.out.println(ob2.getBookName() + " = " + ob1.getBookName());
} else
{
System.out.println(ob2.getBookName() + " != " + ob1.getBookName());
}
System.out.println();
System.out.println(" Comparing Books using Comparable: ");
if (ob1.compareTo(ob2) == 1)
{
System.out.println(ob1.getBookName() + " = " + ob2.getBookName());
} else
{
System.out.println(ob1.getBookName() + " != " + ob2.getBookName());
}
System.out.println();
if (ob2.compareTo(ob3) == 1)
{
System.out.println(ob2.getBookName() + " = " + ob3.getBookName());
} else
{
System.out.println(ob2.getBookName() + " != " + ob3.getBookName());
}
System.out.println();
if (ob3.compareTo(ob1) == 1)
{
System.out.println(ob3.getBookName() + " = " + ob1.getBookName());
} else

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

{
System.out.println(ob3.getBookName() + " != " + ob1.getBookName());
}
System.out.println();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-7
1). Write a program for creating a Bank class, which is used to
manage the bank account of customers. Class has two
methods, Deposit () and withdraw (). Deposit method display old
balance and new balance after depositing the specified amount.
Withdrew method display old balance and new balance after
withdrawing. If balance is not enough to withdraw the money, it
throws ArithmeticException and if balance is less than 500rs after
withdrawing then it throw custom exception,
NotEnoughMoneyException.

import java.util.*;

class NotEnoughMoneyException extends Exception {


String except;

NotEnoughMoneyException() {
except = "Not Enough Balance After Withdrawal!";
}

NotEnoughMoneyException(String e) {
except = e;
}

public String toString() {


return except;
}

public String getMessage() {


return except;
}
}

class Bank{
public Scanner inp=new Scanner(System.in);
double balance;
String name,acc_type;

Bank(){
System.out.print("Account Holder Name: ");
name=inp.nextLine();

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

System.out.print("\nAccount type: ");


acc_type=inp.nextLine();
System.out.print("\nBalance: ");
balance=inp.nextDouble();
}

void Deposit(){
double dep;
System.out.print("\nEnter amount to Deposit: ");
dep=inp.nextDouble();
System.out.print("\nBalance before Deposit: "+balance);
balance+=dep;
System.out.print("\nBalance after Deposit: "+balance);
}

void Withdraw(){
double withd;
System.out.print("\nEnter amount to withdraw: ");
withd=inp.nextDouble();
System.out.print("\nBalance before withdrawal: "+balance);
try{
if(withd>balance){
throw new ArithmeticException("Not Enough Balance");
}
else{
balance-=withd;
System.out.print("\nBalance after Withdrawal: "+balance);
if(balance<500){
throw new NotEnoughMoneyException("Not Enough Money in Account");
}
}
}catch(ArithmeticException e){
System.out.print("\nException: "+e.getMessage());
}catch(NotEnoughMoneyException e){
System.out.print("\nException: "+e.getMessage());
}
}

void display(){
System.out.print("\nAccount Holder: "+name);
System.out.print("\nAccount type: "+acc_type);
System.out.print("\nAccount Balance: "+balance);
}
}

class Demo{
public static void main(String args[]){
Scanner inp=new Scanner(System.in);
Bank ob1=new Bank();
int choice;

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

System.out.print("\n****Menu****");
System.out.print("\n 1.Deposit");
System.out.print("\n 2.Withdraw");
System.out.print("\n 3.Display Account Details");
System.out.print("\n 4.Exit");
do{
System.out.print("\nEnter your choice: ");
choice=inp.nextInt();
switch(choice){
case 1:
ob1.Deposit();
break;

case 2:
ob1.Withdraw();
break;

case 3:
ob1.display();
break;

case 4:
System.out.print("BYE! Come Back Soon");
break;

default:
System.out.print("Invalid Entry");
break;
}
}while(choice!=4);
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2). Write a complete program for calculation average of n +ve


integer numbers of Array
A.
a. Read the array form keyboard
b. Raise and handle Exception if
i. Element value is -ve or non-integer.
ii. If n is zero.
import java.util.*;

class NegativeNumberException extends Exception {


int neg;

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

NegativeNumberException(int neg) {
this.neg = neg;
}

public String toString() {


return neg+" is a Negative number";
}

public String getMessage() {


return neg+ "is Negative no.";
}
}

class NonIntegerException extends Exception {


int nint;

NonIntegerException(int nint){
this.nint=nint;
}
public String toString() {
return "Input is a Non-Integer Value";
}
public String getMessage() {
return nint+ "is Non-Integer no.";
}
}

class ZeroNumberException extends Exception {


int nzero;

ZeroNumberException(int nzero){
this.nzero=nzero;
}
public String toString() {
return "Input is Zero";
}
public String getMessage() {
return nzero+ "is Zero.";
}
}

class Average{
public Scanner inp = new Scanner(System.in);
double avg = 0;
int sum = 0;
int arr[], n;

Average(){
System.out.print(" Enter number of elements: ");
n=inp.nextInt();

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

arr = new int[n];

System.out.print("Enter Array elements: \n");


for(int i=0;i<n;i++){
arr[i]=inp.nextInt();
}
}

void calculate(){
for(int i=0;i<n;i++) {
try{
if(arr[i] > 0 && arr[i] != 0){
sum += arr[i];
}
else if(arr[i] < 0){
throw new NegativeNumberException(arr[i]);
}
else if(arr[i] == 0){
throw new ZeroNumberException(arr[i]);
}
else{
throw new NonIntegerException(arr[i]);
}
}catch(NegativeNumberException e) {
System.out.println(" Exception : " +e.getMessage());
}catch(NonIntegerException e) {
System.out.println(" Exception : " +e.getMessage());
} catch (ZeroNumberException e) {
System.out.println(" Exception : " +e.getMessage());
}
}
avg=sum/n;
System.out.println("\n Average of +ve Integer Values: " + avg);
}
}

class Demo{
public static void main(String args[]){
Average ob1=new Average();
ob1.calculate();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-8
1.Write a program to find prime numbers in a given range using both
methods of multithreading. Also run the same program using executor
framework.

Output:
import java.io.*;
import java.util.*;
class Thread1 extends Thread
{
int max;
public void run()
{
Scanner scan = new Scanner(System.in);
System.out.println("Normal By Extending Thread");
System.out.println("Enter Max Range ");
max = scan.nextInt();
int temp = 0;
try {
for (int i = 0; i <= max; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
temp = 0;
break;
} else {
temp = 1;
}
}
if (temp == 1) {
System.out.println(i);
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
class Thread2 implements Runnable
{
@Override
public void run()
{
Scanner scan = new Scanner(System.in);
System.out.println("Normal By Implementing Runnable");
System.out.println("Enter Max Range ");
int max = scan.nextInt();

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

int temp = 0;
try {
for (int i = 0; i <= max; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {
temp = 0;
break;
} else {
temp = 1;
}
}
if (temp == 1) {
System.out.println(i);
Thread.sleep(1000);
}
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
class P0801
{
public static void main(String args[])
{
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
Thread t = new Thread(t2);
t.start();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2.Assume one class Queue that defines a queue of fixed size says 15.
● Assume one class producer which implements Runnable, having priority
NORM_PRIORITY +1
● One more class consumer implements Runnable, having priority
NORM_PRIORITY-1
● Class TestThread has a main method with maximum priority, which creates 1
thread for producer and 2 threads for consumer.
● Producer produces a number of elements and puts them on the queue. when
the queue becomes full it notifies other threads.
Consumer consumes a number of elements and notifies other threads when the
queue becomes empty.

Code:
class Item
{
int num;
boolean valueSet = false;
public synchronized void put(int num)
{
while (valueSet)
{
try {
wait();
} catch (Exception e) {}
}
System.out.println("Put : " + num);
this.num = num;
valueSet = true;
notify();
}
public synchronized void get()
{
while (!valueSet)
{
try {
wait();
} catch (Exception e) {}
}
System.out.println("Get : " + num);
valueSet = false;
notify();
}
}
class Producer implements Runnable
{
Item item;
public Producer(Item item)
{

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

this.item = item;
Thread produce = new Thread(this, "Producer");
produce.start();
}
public void run()
{
int i = 0;
while (true)
{
item.put(i++);
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}
class Consumer implements Runnable
{
Item item;
public Consumer(Item item)
{
this.item = item;
Thread consume = new Thread(this, "Consumer");
consume.start();
}
public void run()
{
while (true)
{
item.get();
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}
class P0802
{
public static void main(String[] args)
{
Item item = new Item();
new Producer(item);
new Consumer(item);
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-9
1.Write a program to demonstrate user of ArrayList, LinkedList,
LinkedHashMap, TreeMap and HashSet Class. And also implement CRUD
operation without database connection using Collection API.
Code:
import java.util.*;
class PR_9_1
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
System.out.println("This is Array list");
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println(list);
System.out.println("");
System.out.println("This is Linked List");
LinkedList<String> al = new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr = al.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("");
System.out.println("This is LinkedListHashMap");
LinkedHashMap<Integer, String> hm = new
LinkedHashMap<Integer, String>();
hm.put(100, "Amit");
hm.put(101, "Vijay");
hm.put(102, "Rahul");
for (Map.Entry m : hm.entrySet())
{
System.out.println(m.getKey() + " " + m.getValue());
}
System.out.println("");
System.out.println("This is TreeMap");
TreeMap<Integer, String> map = new TreeMap<Integer,
String>();
map.put(100, "Amit");
map.put(102, "Ravi");
map.put(101, "Vijay");

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

map.put(103, "Rahul");
System.out.println("Before invoking remove() method");
for (Map.Entry m : map.entrySet())
{
System.out.println(m.getKey() + " " + m.getValue());
}
map.remove(102);
System.out.println("After invoking remove() method");
for (Map.Entry m : map.entrySet())
{
System.out.println(m.getKey() + " " + m.getValue());
}
System.out.println("");
System.out.println("This is HashSet");
HashSet<String> set = new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i = set.iterator();
while (i.hasNext())
{
System.out.println(i.next());
}
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2.Write a program to Sort Array, ArrayList, String,List, Map and Set.

Code:
import java.util.*;

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

class PR_9_2
{
public static void main(String[] args)
{
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 520,
1123, 366, 420 };
System.out.println("Before Sorting Array:" +
Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("After Sorting Array:" +
Arrays.toString(numbers));
System.out.println();
System.out.println("Sorting of arraylist");
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(7);
list.add(2);
list.add(5);
System.out.println("Before Sorting: " + list);
Collections.sort(list);
System.out.println("After Sorting: " + list);
System.out.println();
System.out.println("Sorting of String");
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Volkswagen");
list1.add("Toyota");
list1.add("Porsche");
list1.add("Ferrari");
list1.add("Mercedes-Benz");
list1.add("Audi");
list1.add("Rolls-Royce");
list1.add("BMW");
System.out.println("Before Sorting: " + list1);
Collections.sort(list);
System.out.println("After Sorting: " + list1);
System.out.println();
System.out.println("Sorting of List");
List<Integer> list3 = Arrays.asList(10, 1, -20, 40, 5, -23, 0);
System.out.println("Before sorting:" + list3);
Collections.sort(list3);
System.out.println("Before sorting:" + list3);
System.out.println();
System.out.println("Sorting of Map");
HashMap<Integer, String> hm = new HashMap<Integer,
String>();
hm.put(23, "Yash");
hm.put(17, "Arun");
hm.put(15, "Swarit");
hm.put(9, "Neelesh");

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Iterator<Integer> it = hm.keySet().iterator();
System.out.println("Before Sorting");
while (it.hasNext())
{
int key = (int) it.next();
System.out.println("Roll no:" + key + " name: " + hm.get(key));
}
Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println("After Sorting");
TreeMap<Integer, String> tm = new TreeMap<Integer,
String>(hm);
Iterator itr = tm.keySet().iterator();
while (itr.hasNext())
{
int key = (int) itr.next();
System.out.println("Roll no:" + key + " name: " + hm.get(key));
}
System.out.println();
System.out.println("Sorting of Set");
HashSet<Integer> numbersSet = new
LinkedHashSet<>(Arrays.asList(15, 11, 9, 55, 47, 18, 1123,
520, 366, 420));
List<Integer> numbersList = new
ArrayList<Integer>(numbersSet); // set -> list
System.out.println("Before Sorting Set:" + numbersList);
Collections.sort(numbersList);
numbersSet = new LinkedHashSet<>(numbersList); // list -> set
System.out.println("After Sorting Set:" + numbersSet);
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-10
1.Write a programme to count occurrence of a given words in a file.

Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

class WordCount
{
public static void main(String args[])
{
String line;
int count = 0;
FileReader file;
BufferedReader br;
try {
file = new FileReader("data.txt");
br = new BufferedReader(file);

while ((line = br.readLine()) != null) {


String word[] = line.split(" ");
System.out.print(line);
count = count + word.length;
}
br.close();
} catch (IOException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("\nNo. of Words =" + count);
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2.Write a program to print itself.


Code:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

class PrIO {
public static void main(String args[]) {
String line;
int count = 0;
FileInputStream file;
int i = 0;
BufferedInputStream br;
try {
file = new FileInputStream("data.txt");
br = new BufferedInputStream(file);

while ((i = br.read()) != -1) {


System.out.print((char) i);
}
br.close();
} catch (IOException e) {
System.out.print(e);
} catch (Exception e) {
e.getStackTrace();
}
}
}
Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

3.Write a program to display list of all the files of given directory.

Code:

import java.util.Scanner;
import java.io.File;

class ListOfFiles {
static void getList(String Dir) {
File f = new File(Dir);
String files[] = f.list();
System.out.println();
System.out.println(" List of Files in " + Dir + " is: ");
System.out.println();
for (String s : files) {
System.out.println(" " + s);
}
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("\n Enter Directory number to display the list of files: ");
String dir = sc.nextLine();
getList(dir);
sc.close();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-11
1.Implement Echo client/server program using TCPInput.

Code:
import java.io.*; import java.net.*;

class P01
{
public static void main(String[] args) throws IOException
{
int portNumber = 12345;
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("Echo server is running on port " + portNumber);
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: "
+clientSocket.getInetAddress().getHostAddress());
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println("Received message from client: " + inputLine);
out.println("Echo: " + inputLine);
}
in.close();
out.close(); clientSocket.close(); serverSocket.close();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2.Write a program using UDP which give name of the audio file to server and
server reply with content of audio file.

Code:
import java.io.*;
import java.net.*;

public class P02


{
public static void main(String[] args) throws IOException
{
int serverPort = 12345;
DatagramSocket serverSocket = new DatagramSocket(serverPort);
System.out.println("Audio server is running on port " + serverPort);
byte[] receiveBuffer = new byte[1024];
while (true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer,
receiveBuffer.length);
serverSocket.receive(receivePacket);
String audioFileName = new String(receivePacket.getData()).trim();
System.out.println("Received request for audio file: " +
audioFileName);
File audioFile = new File(audioFileName);
byte[] audioFileContent = new byte[(int) audioFile.length()];
FileInputStream fileInputStream = new FileInputStream(audioFile);
fileInputStream.read(audioFileContent);
fileInputStream.close();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(audioFileContent,
audioFileContent.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
System.out.println("Sent audio file content to client: " + audioFileName);
serverSocket.close();
}
}
}

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Practical-12
1.Write a programme to implement an investement value calculator using the data
inputed by user. textFields to be included are amount, year, interest rate and future
value. The field “future value” (shown in gray) must not be altered by user.

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class P01 extends JFrame implements ActionListener {


private JLabel amountLabel, yearLabel, rateLabel, futureValueLabel;
private JTextField amountField, yearField, rateField, futureValueField;
private JButton calculateButton, clearButton;

public P01() {
setTitle("Investment Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(5, 2));
amountLabel = new JLabel("Amount:");
amountField = new JTextField(10);
yearLabel = new JLabel("Years:");
yearField = new JTextField(10);
rateLabel = new JLabel("Interest Rate (%):");
rateField = new JTextField(10);
futureValueLabel = new JLabel("Future Value:");
futureValueField = new JTextField(10);
futureValueField.setEditable(false);
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
panel.add(amountLabel);
panel.add(amountField);
panel.add(yearLabel);
panel.add(yearField);
panel.add(rateLabel);
panel.add(rateField);
panel.add(futureValueLabel);
panel.add(futureValueField);
panel.add(calculateButton);
panel.add(clearButton);
add(panel);
setVisible(true);

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

public void actionPerformed(ActionEvent e) {


if (e.getSource() == calculateButton) {
try {
double amount = Double.parseDouble(amountField.getText());
double years = Double.parseDouble(yearField.getText());
double rate = Double.parseDouble(rateField.getText());
double futureValue = amount * Math.pow(1 + rate / 100, years);
futureValueField.setText(String.format("%.2f", futureValue));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "Invalid input!");
}
} else if (e.getSource() == clearButton) {
amountField.setText("");
yearField.setText("");
rateField.setText("");
futureValueField.setText("");
}
}

public static void main(String[] args) {


P01 calculator = new P01();
}
}

Output:

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

2.Write a program which fill the rectangle with the selected color when button
pressed.

Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class P02 extends JFrame implements ActionListener {


private JButton button;
private JPanel panel;
private Color color;

public P02() {
super("Fill Rectangle");
button = new JButton("Select Color");
button.addActionListener(this);
color = Color.RED;
panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(50, 50, 100, 100);
}
};
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setLocationRelativeTo(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


// Open a color chooser dialog and update the panel color
color = JColorChooser.showDialog(this, "Select a color", color);
panel.repaint();
}

public static void main(String[] args) {


new P02();
}
}

[Author] [Author]ANTHAN VALAND


102044502 | Programming with Java

Output:

[Author] [Author]ANTHAN VALAND

You might also like