JAVA
JAVA
PRACTICAL – 1
Basic Program
Step 2: Click on New Button -> Enter PATH as a variable name and copy the
click on OK.
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);
Output :
PRACTICAL – 2
Array:
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){
}
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();
a.printArray();
System.out.print("Maximum of Array: ");
a.maximumOfArray();
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(" ");
}
}
System.out.println();
}
}
}
System.out.println();
}
}
float max=mat[0]
[0]; for (float[] fs :
mat) { for (float ele :
fs) { if(max<ele){
max=ele;
}
}
}
return max;
}
}
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);
b.readMatrix();
b.transpose();
b.multiplication(mat2);
b.displayMatrix(mat2);
b.displayMatrix();
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:
String s3=new
String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
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{
class pr02_5{
public static void main(String args[]){
Scanner scanner = new
PRACTICAL – 3
class BankAccount<acc_no> {
String depositor_name;
static int acc_no = 0;
String acc_type;
private int
balance;
void balanceInquiry(){
System.out.println(balance);
}
one.createAccount("Harsh","Savings");
one.deposit(25000);
one.withdraw(2000);
one.balanceInquiry();
two.createAccount("Darsh","Business");
one.deposit(450000); one.withdraw(60000);
one.balanceInquiry();
}
Output:
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;
}
}
Output:
3. Define a class with the Name, Basic salary and dearness allowance as data
members.Calculate and print the Name, Basic salary(yearly), dearness
allowance and tax deduced at source(TDS) and net salary, where TDS is
charged on gross salary which is basic salary + dearness allowance and
TDS rate is as per following table.
}
}
Output:
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);
}
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)
}
}
return encryptedString;
}
CAESAR CIPHER
import java.io.*;
import java.util.*;
class Cipher
{
public static final String str="abcdefghijklmnopqrstuvwxyz";
{
int charpos=str.indexOf(plaint.charAt(i));
int keyval=(charpos+key)%26;
char replaceval=str.charAt(keyval);
ciphert=ciphert+replaceval;
}
return ciphert;
}
{
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:
Interface
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;
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:
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(){
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()
}
class CPU
{
public CPU(){}
double price = 45000.0;
static class Processor
{
public Processor() {}
double cores = 16.0;
String manufacturer = "AMD";
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
{
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();
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;
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:
import java.util.Scanner;
try {
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
if (arr[i] == 0) {
throw new EnteredValueIsZero();
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output:
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)
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:
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);
}
class producer implements Runnable{
p.start();
p.join();
c1.start();
}
}
Output:
PRACTICAL – 9.1
import java.util.*;
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)
;
}
//TREEMAP
System.out.println("\nTREE MAP:");
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());
}
}
}
Output:
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 ) {
//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) );
//MAP
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:
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:
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:
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);
System.out.println( "********************************
**************");
System.out.println(
"Files from main directory : " + maindir);
System.out.println(
"**********************************************");
for (File file : arr) {
System.out.println(file.getName());
}
}
}
}
Page 49
MADHUBEN & BHANUBHAI PATEL INSTITUTE OF TECHNOLOGY
(A CONSTITUENT COLLEGE OF CVM UNIVERSITY)
DEPARTMENT OF COMPUTER ENGINEERING
PRAGRAMMING WITH JAVA-(102040403)
Output:
PRACTICAL- 11
Networking :
import java.net.*;
import java.io.*;
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:-
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.*;
while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
// 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);
}
}
}
Output:-
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 InvestmentCalculator() {
// Create the main frame
JFrame frame = new JFrame("Investment Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output:-
Write a program which fill the rectangle with the selected color when button pressed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public ColorRectangle() {
// Create the main frame
JFrame frame = new JFrame("Color Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
// 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);
}
}