CTRL C+V
CTRL C+V
PRACTICAL – 1
Basic Program
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%]]
Code:
public class Demo {
System.out.println("Hello World!");
}
}
Output:
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;
a = ob.nextFloat();
// Scanner ob1 = new Scanner(System.in);
b = ob.nextFloat();
switch(select)
{
case 1 :
{
System.out.println("Addition :"+a+" + "+b+" = "+(a+b));
}
break;
case 2 :
{
System.out.println("Subtraction :"+a+" - "+b+" = "+(a-b));
}
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 :
PRACTICAL – 2
Array:
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()
{
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])
{
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;
a1.sort_array();
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*/
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++)
{
{
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....");
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:
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:
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);
sb.append(", I am mutable");
System.out.println("\nsb after updation: " + sb);
sb.reverse();
System.out.println("Reversing sb: " + sb);
}
}
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++)
{
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:
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);
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]
System.out.println("\n==================================================\
n");
System.out.println("\nBalance in Account is::"+bal);
}
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]
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:
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);
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 display() {
System.out.print("\nPlayer Name: " + this.Name);
System.out.print("\nPlayer Age: " + this.Age);
}
}
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);
}
}
25
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
28
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
}
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);
}
}
36
Programming in Java: 102044502
Vishnu Makupalli : 12102130501074
2nd YEAR CSD
}
}
//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
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.*;
InvoiceDetail() {
}
public N getAmount()
{
return amount;
}
public N getDiscount()
{
return Discount;
}
class ExecuteInvoiceDetails
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String INVOICE_NAME;
double DISCOUNT, AMOUNT;
System.out.println("--------------------------------------------");
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();
}
}
Output:
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);
}
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)
System.out.println();
Output:
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;
Book(String bn)
{
this.BOOK_NAME = bn;
}
String getBookName()
{
return BOOK_NAME;
}
class ExecuteBook
{
public static void main(String[] args)
{
Book ob1 = new Book("Java"),
ob2 = new Book("Python"),
ob3 = new Book("Java");
{
System.out.println(ob3.getBookName() + " != " + ob1.getBookName());
}
System.out.println();
}
}
Output:
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.*;
NotEnoughMoneyException() {
except = "Not Enough Balance After Withdrawal!";
}
NotEnoughMoneyException(String e) {
except = e;
}
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();
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;
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:
NegativeNumberException(int neg) {
this.neg = neg;
}
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.";
}
}
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();
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:
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();
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:
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)
{
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:
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");
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:
Code:
import java.util.*;
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");
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:
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);
Output:
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);
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);
}
}
Output:
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:
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.*;
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.*;
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);
Output:
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.*;
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);
}
Output: