0% found this document useful (0 votes)
4 views

JAVA

java file for programs

Uploaded by

Dhairya Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JAVA

java file for programs

Uploaded by

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

MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY

(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)


DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 1

Basic Program

1. Study of 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 a Environment Variables Dialog box by search box

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

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

click on OK.

DHAIRYA PATEL -12202080701030 Page 1


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 2


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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

2. Write a program to
 To prints Fibonacci series.
class Fibonacci{
public static void main(String args[])
{
int x=0, y=1, z, count=10;
System.out.print(x+"
"+y);

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


{
z= x+y;
System.out.print(" "+z);
x = y;
y = z;
}
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 3


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 4


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

 Implement command line calculator


import java.util.Scanner;
public class main {
public static void main(String[] args)
{ double n1;
double n2;
double ans;
char op;
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers:");
n1=sc.nextDouble();
n2=sc.nextDouble();
System.out.println("Enter the operator(+,-,*,/): ");
op=sc.next().charAt(0);
switch (op)
{
case '+' : ans = n1 + n2;
break;
case '-' : ans = n1 - n2;
break;
case '*' : ans = n1 * n2;
break;
case '/' : ans = n1 / n2;
break;
default :
System.out.println("\n Error! Enter correct operator");
return ;
}
System.out.println("The result is:");
System.out.printf(n1 + ""+op + "" + n2 + " = " + ans);
}
}

Output :

DHAIRYA PATEL -12202080701030 Page 5


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING 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.

import java.util.Arrays;
class Array{
public int [] data;

public Array(){
int[] data;
}
public Array(int n){
int[] data = new int[n];
}
public Array(int... arr){

DHAIRYA PATEL -12202080701030 Page 6


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

int[] data = new int[arr.length];


this.data = arr;
}
void printArray(){
for (int i = 0; i < data.length; i++) System.out.println("Element at index " + i + " : " +
data[i]);
}
void reverseArray(){
int l = data.length;
int n = Math.floorDiv(l,2);
int temp;
for (int i = 0;i<n;i++){
temp = data[i];
data[i] = data[l-1-
i]; data[l-1-i] =
temp;
}
}
void maximumOfArray(){
int max = Integer.MIN_VALUE;
for (int e: data){
if (e>max)
max = e;
}
System.out.println(max);
}
void averageOfArray(){
int sum = 0;
for (int i =0;i<=data.length-1;i++) {

DHAIRYA PATEL -12202080701030 Page 7


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
sum += data[i];

DHAIRYA PATEL -12202080701030 Page 8


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

}
System.out.println(sum/data.length);
}
void sorting(){
Arrays.sort(data);
for (int e:data) {
System.out.println(e);
}
}
void display(int n) {
System.out.println("The value of your variable is: "+data[n]);
}
void search(int n){
for (int i = 0;i < data.length;i++) {
if (n == data[i])
System.out.println(i);
}
}
void size(){
System.out.println("Size of Array: "+data.length);
}
}
public class pr02_1 {
public static void main(String[] args) {
Array a = new Array(94,5,6,55,87,545);
System.out.println("Printing Array: ");
a.printArray();
System.out.println("Reverse Array:");
a.reverseArray();

DHAIRYA PATEL -12202080701030 Page 9


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

a.printArray();
System.out.print("Maximum of Array: ");
a.maximumOfArray();

System.out.print("Average of Array: ");


a.averageOfArray();
System.out.println("Sorted Array:");
a.sorting();
a.display(3);
a.search(55);
a.size();
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 10


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

2. Define a class Matrix with


following Field:
int row, column;
float mat[][]
Function:
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

class Matrix{
int row,column;
float mat[][] = {{4,5},{7,8}};
public Matrix(int a[][]){}
public Matrix(){}
public Matrix(int row,int column){}
public void readMatrix(){
for (int i=0;i<2;i++){
for (int j=0;j<2;j++)
System.out.print((int)mat[i][j]+" ");
System.out.println(" ");
}
}

DHAIRYA PATEL -12202080701030 Page 11


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public void transpose()


{
float [][]transpose = new float[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
transpose[i][j]= mat[j][i];
}
}
System.out.println("TRANSPOSE:");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
System.out.print((int)transpose[i][j]+" ");
}
System.out.println();//new line
}
}

public void multiplication(float[][] mat2){


float[][] c = new float[2][2];
System.out.println("MULTIPLICATION:");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){ c[i]
[j]=0;
for(int k=0;k<2;k++)
{
c[i][j]+=mat[i][k]*mat2[k][j];
}
System.out.print((int)c[i][j]+" ");
}

DHAIRYA PATEL -12202080701030 Page 12


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

System.out.println();
}
}

public void displayMatrix(float[][] a){


System.out.println();
System.out.println("MATRIX given: ");
for (float[] fs : a) {
for (float ele : fs) {
System.out.print(ele + " ");

}
System.out.println();
}
}

public void displayMatrix(){


System.out.println();
System.out.println("MATRIX : ");
for (float[] fs : mat) {
for (float ele : fs) {
System.out.print(ele + " ");
}
System.out.println();
}

public float maximum_of_array(){

DHAIRYA PATEL -12202080701030 Page 13


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

float max=mat[0]
[0]; for (float[] fs :
mat) { for (float ele :
fs) { if(max<ele){
max=ele;
}
}
}
return max;
}

public float average_of_array( ){


float sum=0,avg,i=0;
for (float[] fs : mat)
{ for (float ele :
fs) { i++;
sum+=ele;
}
}
avg=sum/i;
return avg;
}

}
public class pr02_2 {
public static void main(String[] args) {
Matrix a = new Matrix(new int [10][10]);
Matrix b = new Matrix();
Matrix c = new Matrix(2,5);

DHAIRYA PATEL -12202080701030 Page 14


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

float[][] mat2 = {{4,5},{6,9}};

b.readMatrix();
b.transpose();
b.multiplication(mat2);
b.displayMatrix(mat2);
b.displayMatrix();

System.out.println("Average of an array is :"+b.average_of_array());


System.out.println("Maximum of an array is :"+b.maximum_of_array());
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 15


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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

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

Integer myInt = 6;
Double myDouble =
6.99; Character myChar
= 'A';

System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());

System.out.println(myChar.charValue());
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 16


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 17


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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

public class pr02_4 {


public static void main(String[] args) {
String s1="java";
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);

String s3=new
String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

StringBuffer sb = new StringBuffer("Hello My name is Vrushabh


Paneliya"); sb.append(" Paneliya");
sb.delete(2,5);
sb.insert(2,"llo");
sb.replace(0,5,"holaa");
sb.reverse();
System.out.println(sb);
System.out.println(sb.capacity());
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 18


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 19


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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”

import java.util.Scanner;
class Cipher1{

DHAIRYA PATEL -12202080701030 Page 20


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

private String plaintxt;


private String ciphertxt;

public Cipher1(String txt){


this.plaintxt = txt;
}

public String encrypt(){


char[] ptxt = plaintxt.toCharArray();

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


ptxt[i] = (char)(ptxt[i]+3);
}
this.ciphertxt = new String(ptxt);
return new String(ptxt);
}
public String decrypt(){
char[] ptxt = ciphertxt.toCharArray();

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


ptxt[i] = (char)(ptxt[i]-3);
}
return new String(ptxt);
}
}

class pr02_5{
public static void main(String args[]){
Scanner scanner = new

DHAIRYA PATEL -12202080701030 Page 21


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
Scanner(System.in);

DHAIRYA PATEL -12202080701030 Page 22


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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


String data = scanner.nextLine();
Cipher1 cipher = new Cipher1(data);

System.out.println("Cipher Text : " + cipher.encrypt());


System.out.println("Plain Text : " + cipher.decrypt());
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 23


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 3

Basic Program using Class

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

class BankAccount<acc_no> {
String depositor_name;
static int acc_no = 0;
String acc_type;
private int
balance;

public void createAccount(String name,String type) {


depositor_name = name;
acc_type =
type; acc_no++;
}

void deposit(int n){ balance += n;}

void withdraw(int n){balance -= n;}

void balanceInquiry(){
System.out.println(balance);
}

DHAIRYA PATEL -12202080701030 Page 24


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
}

DHAIRYA PATEL -12202080701030 Page 25


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public class pr03_1 {


public static void main(String[] args) {
BankAccount one = new BankAccount();
BankAccount two = new
BankAccount();

one.createAccount("Harsh","Savings");
one.deposit(25000);
one.withdraw(2000);
one.balanceInquiry();

System.out.println("Account number of "+ one.depositor_name+" is "+BankAccount.acc_no);

two.createAccount("Darsh","Business");
one.deposit(450000); one.withdraw(60000);
one.balanceInquiry();

System.out.println("Account number of "+two.depositor_name+" is "+BankAccount.acc_no);

}
Output:

DHAIRYA PATEL -12202080701030 Page 26


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 27


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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.

import java.util.Calendar;

public class pr03_2{


public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date: "+calendar.getTime());
calendar.add(Calendar.HOUR,5);
System.out.println("5 minutes is added to time then it will be:
"+calendar.getTime());

}
}
Output:

DHAIRYA PATEL -12202080701030 Page 28


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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.

Gross Salary TDS


Rs. 100000 and below NIL
Above Rs. 100000 10% on excess over
100000
DA is 74% of Basic Salary for all. Use appropriate member function.
class employee{
String name;
int basicSalary;
double DA;
employee(String name,int basicSalary){
this.name = name;
this.basicSalary = basicSalary;
this.DA = 0.74 * basicSalary;
}
public double grossSalary(){
return basicSalary + DA;
}
public double tds(){
double tds = 0;
if (grossSalary()<=100000 )
tds = 0;
else if (grossSalary()>100000)
tds = grossSalary() * 0.1;
return tds;
}
double netSalary(){

DHAIRYA PATEL -12202080701030 Page 29


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

return grossSalary() - tds();


}
void getInformation(){
System.out.println("Name of the employee: "+name);
System.out.println("Basic Salary of the employee: "+basicSalary);
System.out.println("Dearness Allowance of the salary: "+DA);
System.out.println("TDS of the salary: "+tds());
System.out.println("Net Salary of the employee: "+netSalary());
}
}
public class pr03_3 {
public static void main(String[] args) {
employee a = new employee("Darsh",50000);
a.getInformation();

}
}
Output:

DHAIRYA PATEL -12202080701030 Page 30


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 31


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 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 command line and
display the information.

import java.util.Scanner;

class cricket{
String name;
int age;

void display(){
System.out.println("The name of the player is "+name+" and age is "+age);
}

cricket(String name,int age){


this.name = name;
this.age = age;
}
}

class match extends cricket{


int noOfOdi, noOfTest;

public void setNoOfOdi(int noOfOdi) {


this.noOfOdi = noOfOdi;

DHAIRYA PATEL -12202080701030 Page 32


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
}

DHAIRYA PATEL -12202080701030 Page 33


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public void setNoOfTest(int noOfTest) {


this.noOfTest = noOfTest;
}

match(String name,int age,int noOfOdi,int noOfTest){


super(name,age);
this.noOfOdi = noOfOdi;
this.noOfTest = noOfTest;
}

public void printInfo(){


display();
System.out.println("The number of ODI and TEST matches played are
"+noOfOdi+" and "+noOfTest);
}
}

public class pr04_1 {


public static void main(String[] args) {

match m = new match("Darsh Pandya",22,58,65);


m.printInfo();
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 34


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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
Encyption() and Decyption() Method. in substitute cipher every character of
string is replace 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.

SUBSTITUTION CIPHER

import java.io.*;
import java.util.Scanner;
DHAIRYA PATEL -12202080701030 Page 35
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public class newCipher {


public static char normalChar[]
= { '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' };

public static char codedChar[]


= {'z' ,'y' ,'x' ,'w' ,'v' ,'u' ,'t' ,'s'
,'r' ,'q' ,'p' ,'o' ,'n' ,'m' ,'l' ,'k' ,'j'
,'i' ,'h' ,'g' ,'f' ,'e' ,'d' ,'c' ,'b' ,'a'} ;

public static String stringEncryption(String s)


{

String encryptedString = "";


for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < 26; j++) {
if (s.charAt(i) == normalChar[j])
{
encryptedString += codedChar[j];
break;
}

}
}

return encryptedString;
}

DHAIRYA PATEL -12202080701030 Page 36


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public static String stringDecryption(String s)


{
String decryptedString = "";
for (int i = 0; i < s.length(); i+
+)
{
for (int j = 0; j < 26; j++) {
if (s.charAt(i) == codedChar[j])
{
decryptedString += normalChar[j];
break;
}
}
}
return decryptedString;
}
public static void main(String args[])
{
System.out.println("Enter the text:
"); Scanner s = new
Scanner(System.in); String str =
s.nextLine();

System.out.println("Plain text: " + str);

String encryptedString = stringEncryption(str.toLowerCase());

System.out.println("Encrypted message: "

DHAIRYA PATEL -12202080701030 Page 37


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
+ encryptedString);

DHAIRYA PATEL -12202080701030 Page 38


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

System.out.println("Decrypted message: "


+ stringDecryption(encryptedString));
}
}
Output:

CAESAR CIPHER
import java.io.*;
import java.util.*;
class Cipher
{
public static final String str="abcdefghijklmnopqrstuvwxyz";

public static String encrypt(String plaint,int key)


{
plaint=plaint.toLowerCase();
String ciphert="";
for(int i=0;i<plaint.length();i++)

DHAIRYA PATEL -12202080701030 Page 39


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

{
int charpos=str.indexOf(plaint.charAt(i));
int keyval=(charpos+key)%26;
char replaceval=str.charAt(keyval);
ciphert=ciphert+replaceval;
}
return ciphert;
}

public static String decrypt(String ciphert,int key)


{
ciphert=ciphert.toLowerCase();
String plaint="";
for(int i=0;i<ciphert.length();i++)
{
int charpos=str.indexOf(ciphert.charAt(i));
int keyval=(charpos-key)%26;
if(keyval<0)
{
keyval=str.length()+keyval;
}
char replaceval=str.charAt(keyval);
plaint=plaint+replaceval;
}
return plaint;
}

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

DHAIRYA PATEL -12202080701030 Page 40


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedReader kr=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a plain text: ");
String msg=br.readLine();
System.out.print("Enter a key: ");
String key=br.readLine();
int k=Integer.parseInt(key);
System.out.println("Encrypted Text: "+encrypt(msg,k));
System.out.println("Decrypted Text: "+decrypt(encrypt(msg,k),k));
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 41


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

Interface

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

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.
interface Property{
int ConstructionCost=500;
int AddCostFlat=200000;
int AddCostBun=200;
int LandCost=400;
float computePrice();
}
class Bungalow implements Property{
String name;
float constructionArea;
float landArea;
Bungalow(String name, float constructionArea, float landArea){
this.name=name;
this.constructionArea=constructionArea;

DHAIRYA PATEL -12202080701030 Page 42


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

this.landArea=landArea;
}
public float computePrice(){
return constructionArea*(ConstructionCost+AddCostBun)+landArea*LandCost;
}
}
class Flat implements Property{
String name;
float constructionArea;
Flat(String name, float constructionArea){
this.name=name;
this.constructionArea = constructionArea;
}
public float computePrice(){
return constructionArea*ConstructionCost + AddCostFlat;
}
}
public class pr04_3{
public static void main(String[] args) {
Bungalow b=new Bungalow("Rudraksh",10000,1);
Flat f=new Flat("Shyam",2000);
System.out.print("Price for Bungalow: ");
System.out.println(b.computePrice());
System.out.print("Price for Flat: ");
System.out.println(f.computePrice());
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 43


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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;
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 {

DHAIRYA PATEL -12202080701030 Page 44


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

private double radius;


public Sphere (double radius)
public double volume()
public void describe()
}
Define test class to call various methods of Geometric Shape

import java.util.*;
import java.io.*;

interface GeometricShape {
public void describe();
}
interface TwoDShape extends GeometricShape {
public double area();
}
interface ThreeDShape extends GeometricShape {
public double volume();
}
class Cone implements ThreeDShape {
private double radius;
private double height;
public Cone (double radius, double height){
this.height=height;
this.radius=radius;
}
public double volume(){return (double)((.33)*(Math.PI)*(Math.pow(radius,
2))*height); }
public void describe(){

DHAIRYA PATEL -12202080701030 Page 45


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

System.out.println("A cone is a 3D shape consisting of a circular base and once


continuous curved surface tapering to a point (the apex) above the centre of the circular
base.");
}
}
class Rectangle implements TwoDShape {
private double width, height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public double area() {


return height*width;
}

public double perimeter() {


return 2*(height+width);
}

public void describe() {


System.out.println("A rectangle is a 2D shape that has 4 sides, 4 corners, and 4 right
angles");
}
}
class Sphere implements ThreeDShape {
private double radius;
public Sphere (double radius){this.radius=radius;}

DHAIRYA PATEL -12202080701030 Page 46


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public double volume(){return (4/3)*Math.PI*Math.pow(radius, 3);}


public void describe(){System.out.println("A sphere is a perfectly-round 3D shape in
the shape of a ball.");}
}

public class pr04_4 {


public static void main(String[] args) {
Rectangle r=new Rectangle(10, 20);
Sphere s=new Sphere(3);
Cone c=new Cone(4, 5);
System.out.println("Rectangle :");
System.out.println("Area : "+r.area());
r.describe();
System.out.println("Perimeter : "+r.perimeter());
System.out.println();
System.out.println("Sphere :");
System.out.println("Volume : "+s.volume());
s.describe();
System.out.println();
System.out.println("Cone :");
System.out.println(""+c.volume());
c.describe();
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 47


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 48


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 5

Inner Class:

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

class CPU
{
public CPU(){}
double price = 45000.0;
static class Processor
{
public Processor() {}
double cores = 16.0;
String manufacturer = "AMD";

DHAIRYA PATEL -12202080701030 Page 49


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

double getCache()
{
return 16;
}
void displayProcesorDetail()
{
System.out.println("Processor Name: AMD Ryzen 9 6000 Series");
}
}
protected static class RAM
{
double memory = 160000000.00;
String manufacturer = "Crucial";
Double clockSpeed = 320000000000.00;
double getClockSpeed()
{
return clockSpeed;
}
void displayRAMDetail()
{
System.out.println("Ram Name: Crucial");
System.out.println("Ram Speed: 3200Mhz");
System.out.println("Ram Capacity: 16 GB");
}
}
}
public class pr05_1
{

DHAIRYA PATEL -12202080701030 Page 50


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public static void main(String[] args)


{
PU.Processor cpu = new
CPU.Processor(); CPU c = new CPU();
CPU.RAM r = new CPU.RAM();
cpu.displayProcesorDetail();
r.displayRAMDetail();
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 51


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

2. Write a program to demonstrate usage of static inner class, local inner


class and anonymous inner class

class Outer{
static class staticInner{
void myMethod(){
System.out.println("I am method of Static Inner Class.");
}
}
void method(){
int n = 1;
class localInner{
public void print(){
System.out.println("I am method of Local Inner Class.");
}
}
localInner l = new localInner();
l.print();
}
}
abstract class anonymousInner{
public abstract void
method1();
}
public class pr05_2 {
public static void main(String[] args) {
//Implementing Static Inner Class
Outer.staticInner a = new Outer.staticInner();
a.myMethod();

DHAIRYA PATEL -12202080701030 Page 52


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
//Implementing Local Inner Class

DHAIRYA PATEL -12202080701030 Page 53


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

Outer o = new Outer();


o.method();

//Implementing Anonymous Inner Class


anonymousInner inner = new anonymousInner()
{
@Override
public void method1() {
System.out.println("I am method of Anonymous Inner Class.");
}
};
inner.method1();
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 54


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

DHAIRYA PATEL -12202080701030 Page 55


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 7

Exception Handing

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.Scanner;
class NotEnoughMoneyException extends Exception{}
class Bank{
int balance;
public Bank(int balance){
this.balance=balance;
}
void deposit(int deposit){
System.out.println("The available balance is "+balance);
this.balance += deposit;
}
void withdraw(int withdraw) throws ArithmeticException{
System.out.println("The available balance is "+balance);
System.out.println("Withdraw Amount: "+withdraw);
try{
if (balance < withdraw){
throw new ArithmeticException();
}
this.balance -= withdraw;

DHAIRYA PATEL -12202080701030 Page 56


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

try{
if(balance < 500){
throw new NotEnoughMoneyException();
}
}
catch (Exception e){
System.out.println("There is not enough money in your account:"+e);
System.out.println("Minimum requirement of balance is 500.");
}
}
catch (Exception e) {
System.out.println("There is a error "+e);
}
}
}
public class pr07_1 {
public static void main(String[] args) {
Bank b = new Bank(20000);
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount you want to withdraw: ");
int withdraw = s.nextInt();
b.withdraw(withdraw);
}
}
Output:

DHAIRYA PATEL -12202080701030 Page 57


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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


numbers of Array A.
a. Read the array form keybo ard
b. Raise and handle Exception if
i. Element value is -ve or non-integer.
ii. If n is zero.

import java.util.Scanner;

class EnteredValueIsZero extends Exception{}

class EnteredValueIsNegativeOrNonInteger extends Exception{}

public class pr07_2 {


public static void main(String[] args) {

Scanner s = new Scanner(System.in);


System.out.println("Enter the size of your array: ");
int n = s.nextInt();

nt [] arr = new int[n];


System.out.println("Enter the elements of your array: ");

try {
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
if (arr[i] == 0) {
throw new EnteredValueIsZero();
}

if (arr[i] < 0 || !s.hasNextInt()) {


throw new EnteredValueIsNegativeOrNonInteger();
DHAIRYA PATEL -12202080701030 Page 58
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

}
}

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

DHAIRYA PATEL -12202080701030 Page 59


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 8.1
import java.util.Scanner;
class multiThread extends Thread{
int first,last;
public void setValues(int first,int last) {
this.first=first;
this.last=last;
}
public void run(){
for (int i = first;i<= last;i++){
if(isPrime(i)){
System.out.println(i);
}
try{
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean isPrime(int n){
if(n <= 1){
return false;
}
for(int i = 2; i <= Math.sqrt(n);i++){
if (n%i ==0)

12202080701030- DHAIRYA PATEL Page 48

Page 35
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

return false;
}
return true;
}
}
public class pr08_1 {
public static void main(String[] args) {
int first,last;
Scanner s = new Scanner(System.in);
System.out.println("Enter the range of numbers for finding the prime numbers");
System.out.println("Starting: ");
first = s.nextInt();
System.out.println("Ending: ");
last = s.nextInt();
multiThread m = new multiThread();
m.setValues(first,last);
System.out.println("The list of Prime numbers are as follows: ");
m.start();
}
}
Output:

[12202080701030- DHAIRYA PATEL Page 49


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

[12202080701030- DHAIRYA PATEL Page 50


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL-8.2

import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;

class queue{
producer p = new producer();
static PriorityQueue<Integer> queue = new PriorityQueue<Integer>(15);

static void gettingArray(int ...arr){


int count=0;
System.out.println("Adding Elements into Queue: ");
for (int i = 0; i < arr.length; i++) {
queue.add(arr[i]);
count++;
}
System.out.println(queue);
if (queue.isEmpty()){
isEmpty = true;
}
if (count==15){
isFull = true;
}
}
static boolean isFull,isEmpty;

}
class producer implements Runnable{

[12202080701030- DHAIRYA PATEL Page 51


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

public void run(){


produce();
for (int i = 0; i < isize; i++) {
arr[i] = random.nextInt(50);
System.out.println(arr[i]);
}
queue.gettingArray(arr);
}
}

class consumer implements Runnable{


public void run(){
consume();
}
public void consume(){
System.out.println("Enter the number of elements you want to consume: ");
Scanner s = new Scanner(System.in);
int c = s.nextInt();
for (int i = 0; i < c; i++) {
queue.queue.poll();
}
System.out.println("Queue after consuming elements: ");
System.out.println(queue.queue);
}
}
public class pr08_2 {
public static void main(String[] args) throws InterruptedException {

producer pro = new producer();

[12202080701030- DHAIRYA PATEL Page 52


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

consumer con1 = new


consumer(); consumer con2 =
new consumer(); queue q = new
queue();

Thread p = new Thread(pro);


Thread c1 = new
Thread(con1); Thread c2 =
new Thread(con2);
p.setPriority(Thread.NORM_PRIORITY+1);
c1.setPriority(Thread.NORM_PRIORITY-1);
c2.setPriority(Thread.NORM_PRIORITY-1);

p.start();
p.join();
c1.start();

}
}

Output:

[12202080701030- DHAIRYA PATEL Page 53


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

[12202080701030- DHAIRYA PATEL Page 54


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

[12202080701030- DHAIRYA PATEL Page 55


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 9.1

import java.util.*;

public class pr09_1 {


public static void main(String[] args) {
//ARRAYLIST
System.out.println("ARRAYLIST:");
ArrayList<String> cars = new ArrayList<String>();
cars.add("VOLVO");
cars.add("MAYBACH");
cars.add("MERCEDES");
cars.add("AUDI");
cars.add("ROLLS ROYCE");
cars.remove("VOLVO");
System.out.println("Print the first element in the cars[]: "+cars.get(0));
Collections.sort(cars);
for (String i:cars) {
System.out.println(i);
}
//LINKED LIST
System.out.println("\nLINKEDLIST:");
LinkedList<Integer> a = new LinkedList<Integer>();
a.addFirst(8);
a.addLast(4);
a.addFirst(3);
a.addFirst(9);

12202080701030- DHAIRYA PATEL Page 55

Page 40
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

a.addLast(7);
a.removeFirst();
a.removeLast();
System.out.println("FIRST:"+a.getFirst())
;
System.out.println("LAST:"+a.getLast());
System.out.println("ALL:");
for(int i: a) {
System.out.println(i)
;
}

//LINKED HASH MAP

System.out.println("\nLINKED HASH MAP:");


LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(100,"Jenil");
map.put(101,"Parth");
map.put(102,"Sarthik");
map.put(104,"Vrushabh");
System.out.println("Before removing key-104 : "+map);
map.remove(104);
System.out.println("After removing key-104 : "+map);
System.out.println("Keys: "+map.keySet());
System.out.println("Values: "+map.values());
System.out.println("Key-Value pairs: "+map.entrySet());

//TREEMAP

12202080701030- DHAIRYA PATEL Page 56


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

System.out.println("\nTREE MAP:");

12202080701030- DHAIRYA PATEL Page 57


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

TreeMap<Integer,String> map1=new TreeMap<Integer,String>();


map1.put(100,"Amit");

map1.put(102,"Ravi");
map1.put(101,"Vijay");
map1.put(103,"Rahul");
//Maintains descending order
System.out.println("descendingMap: "+map1.descendingMap());
//Returns key-value pairs whose keys are less than or equal to the specified key.
System.out.println("headMap: "+map1.headMap(102,true));
//Returns key-value pairs whose keys are greater than or equal to the specified key.
System.out.println("tailMap: "+map1.tailMap(102,true));
//Returns key-value pairs exists in between the specified key.
System.out.println("subMap: "+map1.subMap(100, false, 102, true));

//HASH SET

System.out.println("\nHASH SET:");
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}

12202080701030- DHAIRYA PATEL Page 58


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

}
Output:

12202080701030- DHAIRYA PATEL Page 59


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL-9.2

import java.util.*;
public class pr09_2
{
public static <Int> void main(String[] args) {
//ARRAY
System.out.println("ARRAY:");
int [] arr = {8,7,9,6,5,2,1,0,4};
System.out.println("The Original array is "+Arrays.toString(arr));
Arrays.sort(arr);
System.out.print("The Sorted array is "+Arrays.toString(arr));

//ARRAYLIST
System.out.println("\nARRAYLIST:");
ArrayList<Integer> nums = new ArrayList<>(5);
nums.add(9);
nums.add(0);
nums.add(6);
nums.add(3);
nums.add(1);
System.out.print("Before Sorting: ");
for (int i:nums ) {
System.out.print(" "+i);
}
Collections.sort(nums);
System.out.println();
System.out.print("After Sorting: ");
for (int i:nums ) {

12202080701030- DHAIRYA PATEL Page 60


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
System.out.print(" "+i);

12202080701030- DHAIRYA PATEL Page 61


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

//STRING
System.out.println("\nSTRING:");
String[] names = {"Jenil","Vatsal","Parth","Sarthik","Vrushabh","Sarang"};
System.out.print("Before Sorting: "+Arrays.toString(names));
Arrays.sort(names);
System.out.println();
System.out.print("After Sorting: "+Arrays.toString(names));

//LIST System.out.println("\
nLIST:");
Integer[] numbers = new Integer[] { 15, 11, 9, 55, 47, 18, 1123, 520, 366, 420 };
List<Integer> numbersList = Arrays.asList(numbers);
Collections.sort(numbersList);

System.out.println(numbersList);
//
//HASHSET
System.out.println("\nHASHSET:");
HashSet<Integer> numbersSet = new LinkedHashSet<>(
Arrays.asList(15, 11, 9, 55, 47, 18, 1123, 520, 366, 420) );

List<Integer> numbersList1 = new ArrayList<Integer>(numbersSet) ;


Collections.sort(numbersList1);
numbersSet = new LinkedHashSet<>(numbersList1);
System.out.println(numbersSet);

//MAP

12202080701030- DHAIRYA PATEL Page 62


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

System.out.println("\nMAP:");
HashMap<Integer, String> map = new HashMap<>();
map.put(50, "JENIL");
map.put(20, "SARTHIK");

map.put(60, "PARTH");
map.put(70, "VATSAL");
map.put(120, "BANSI");
map.put(10, "SMIT");
TreeMap<Integer, String> treeMap = new TreeMap<>(map);
System.out.println("Data is sorted by Key "+treeMap);
}
}
Output:

12202080701030- DHAIRYA PATEL Page 63


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL – 10.1

import java.io.*;
public class pr10_1{
public static void main(String[] args) throws IOException {
String line;
int count = 0;
//Opens a file in read mode
FileReader file = new FileReader("text.txt");
BufferedReader br = new BufferedReader(file);
//Gets each line till end of file is reached
while((line = br.readLine()) != null) {
//Splits each line into words
String words[] = line.split(" ");
//Counts each word
count = count + words.length;
}
System.out.println("Number of words present in given file: " + count);
br.close();
}
}
Output:

12202080701030- DHAIRYA PATEL Page 64


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

12202080701030- DHAIRYA PATEL Page 65


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL-10.2

import java.io.*;
class pr10_2{
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);

fin.close();
}
}
Output:

12202080701030- DHAIRYA PATEL Page 64

Page 48
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL-10.3

import java.io.File;
public class J_3 {
public static void main(String[] args) {
// Provide full path for directory(change accordingly)
String maindirpath=” C:\Users\darsh\Desktop\12002080601014>”;

// File object
File maindir = new File(maindirpath);

if (maindir.exists() && maindir.isDirectory()) {


File arr[] = maindir.listFiles();

System.out.println( "********************************
**************");
System.out.println(
"Files from main directory : " + maindir);
System.out.println(
"**********************************************");
for (File file : arr) {
System.out.println(file.getName());
}
}
}
}

12202040701030- DHAIRYA PATEL Page 65

Page 49
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

Output:

12202080701030- DHAIRYA PATEL Page 66


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL- 11

Networking :

Implement Echo client/server program using TCP

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

public class EchoServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new
ServerSocket(4444)) {
System.out.println("EchoServer started.");
while (true) {
try (Socket clientSocket = serverSocket.accept();
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: " + inputLine);
out.println("Echo: " + inputLine);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Error starting EchoServer: " +
e.getMessage());
}

Output:-

12202080701030- DHAIRYA PATEL Page 67


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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

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

public class AudioServer {


public static void main(String[] args) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);

while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);

// Extract the audio file name from the received packet


String audioFileName = new String(receivePacket.getData(), 0, receivePacket.getLength());

// Read the contents of the audio file into a string


String audioFileContents = "";
try (BufferedReader br = new BufferedReader(new FileReader(audioFileName))) {
String line;
while ((line = br.readLine()) != null) {
audioFileContents += line + "\n";
}
} catch (IOException e) {
audioFileContents = "Error: " + e.getMessage();
}

// Convert the audio file contents to bytes and send them back to the client
byte[] audioFileContentsBytes = audioFileContents.getBytes();
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
DatagramPacket sendPacket = new DatagramPacket(audioFileContentsBytes,
audioFileContentsBytes.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
}
}

12202080701030- DHAIRYA PATEL Page 68


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

Output:-

12202080701030- DHAIRYA PATEL Page 69


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

PRACTICAL- 12
GUI:

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.

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

public class InvestmentCalculator implements ActionListener {


private JTextField amountField;
private JTextField yearField;
private JTextField rateField;
private JTextField futureValueField;

public InvestmentCalculator() {
// Create the main frame
JFrame frame = new JFrame("Investment Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the text fields and labels


JLabel amountLabel = new JLabel("Amount:");
amountField = new JTextField(10);
JLabel yearLabel = new JLabel("Year:");
yearField = new JTextField(10);
JLabel rateLabel = new JLabel("Interest rate:");

12202080701030- DHAIRYA PATEL Page 70


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

rateField = new JTextField(10);


JLabel futureValueLabel = new JLabel("Future value:");
futureValueField = new JTextField(10);
futureValueField.setEditable(false);

// Create the calculate button


JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);

// Create the panel and add the components


JPanel panel = new JPanel(new GridLayout(4, 2));
panel.add(amountLabel);
panel.add(amountField);
panel.add(yearLabel);
panel.add(yearField);
panel.add(rateLabel);
panel.add(rateField);
panel.add(futureValueLabel);
panel.add(futureValueField);

// Add the panel and button to the frame


frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(calculateButton, BorderLayout.SOUTH);

// Set the size and make the frame visible


frame.setSize(300, 150);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event) {


// Get the input values from the text fields
double amount = Double.parseDouble(amountField.getText());
int years = Integer.parseInt(yearField.getText());
double rate = Double.parseDouble(rateField.getText());

// Calculate the future value


double futureValue = amount * Math.pow(1 + rate/100, years);

// Set the future value field


futureValueField.setText(String.format("%.2f", futureValue));
}

public static void main(String[] args) {


InvestmentCalculator calculator = new InvestmentCalculator();
}

12202080701030- DHAIRYA PATEL Page 71


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

Output:-

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

12202080701030- DHAIRYA PATEL Page 72


MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

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

public class ColorRectangle implements ActionListener {


private JPanel rectanglePanel;
private JButton redButton, blueButton, greenButton;

public ColorRectangle() {
// Create the main frame
JFrame frame = new JFrame("Color Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create the rectangle panel and set its color


rectanglePanel = new JPanel();
rectanglePanel.setPreferredSize(new Dimension(200, 200));
rectanglePanel.setBackground(Color.WHITE);

// Create the color buttons


redButton = new JButton("Red");
redButton.addActionListener(this);
blueButton = new JButton("Blue");
blueButton.addActionListener(this);
greenButton = new JButton("Green");
greenButton.addActionListener(this);

// Add the panel and buttons to the frame


JPanel buttonPanel = new JPanel();
buttonPanel.add(redButton);
buttonPanel.add(blueButton);
buttonPanel.add(greenButton);
frame.getContentPane().add(rectanglePanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);

// Set the size and make the frame visible


12202080701030- DHAIRYA PATEL Page 73
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)

frame.pack();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event) {


// Get the source of the event (the button that was pressed)
Object source = event.getSource();

// Set the color of the rectangle panel based on the button that was pressed
if (source == redButton) {
rectanglePanel.setBackground(Color.RED);
} else if (source == blueButton) {
rectanglePanel.setBackground(Color.BLUE);
} else if (source == greenButton) {
rectanglePanel.setBackground(Color.GREEN);
}
}

public static void main(String[] args) {


ColorRectangle colorRectangle = new ColorRectangle();
}
}
Output:-

12202080701030- DHAIRYA PATEL Page 74

You might also like