JAva 4
JAva 4
JAva 4
Practical 5
1. Define two nested classes: Processor and RAM, inside the outer
class: CPU with following data members
class CPU {
double price;
class Processor{
double cores;
double catch()
String manufacturer;
double getCache()
void displayProcesorDetail()
}
protected class RAM { // nested protected class
double memory;
String manufacturer;
Double clockSpeed;
double getClockSpeed()
void displayRAMDetail()
}
}
Write appropriate Constructor and create instance of Outer and inner
class and call the methods in main function
12202040501019 Dharmik Rabadiya
Code:
import java.util.Scanner;
class CPU {
double price;
CPU(double p){
price=p;
}
public void displayprice()
{
System.out.println("Price:"+price);
}
class Processor{ // nested class
double cores;
String manufacturer;
int cache;
Processor(double c, String m)
{
cores=c;
manufacturer=m;
}
public void getCache()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Cache");
cache= sc.nextInt();
12202040501019 Dharmik Rabadiya
}
public void displayProcesorDetail(){
System.out.println("Core:"+ cores);
System.out.println("manufacturer:"+ manufacturer);
System.out.println("cache:"+ cache);
}
}
class RAM{ // nested protected class
// members of protected nested class
double memory;
String manufacturer;
Double clockSpeed;
RAM(double m,String man)
{
memory=m;
manufacturer=man;
}
public void getClockSpeed()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter ClockSpeed");
clockSpeed= sc.nextDouble();
}
public void displayRAMDetail(){
System.out.println("memory:"+ memory);
System.out.println("manufacturer:"+ manufacturer);
System.out.println("clockSpeed:"+ clockSpeed);
}
}
12202040501019 Dharmik Rabadiya
class MainCPU{
public static void main(String args[]){
CPU c = new CPU(50000.0);
CPU.Processor p=c.new Processor(5.0,"Intel");
CPU.RAM r=c.new RAM(16.0,"Intel");
c.displayprice();
p.getCache();
p.displayProcesorDetail();
r.getClockSpeed();
r.displayRAMDetail();
}}
Output:
12202040501019 Dharmik Rabadiya
class NInner{
public void display()
{
System.out.println("Inside Local Inner class");
}
}
interface AnonymousInner{
public void display();
}
12202040501019 Dharmik Rabadiya
class MainInner{
public static void main(String args[])
{
Outer o= new Outer();
o.display();
Output:
Practical 6
12202040501019 Dharmik Rabadiya
this.discount = discount;
}
public N getDiscount() { return discount; }
public void display() {
System.out.println("Invoice Name : " + invoiceName);
System.out.println("Amount : " + amount);
System.out.println("Discount : " + discount + "%");
}}
public class InvoiceMain {
public static void main(String[] args) {
InvoiceDetail<Integer> invoice1 = new InvoiceDetail<Integer>();
invoice1.setInvoiceName("Shrey");
invoice1.setAmount(50000);
invoice1.setDiscount(50);
invoice1.display();
InvoiceDetail<Float> invoice2 = new InvoiceDetail<Float>();
invoice2.setInvoiceName("ABC");
invoice2.setAmount(694.56f);
invoice2.setDiscount(50.5f);
invoice2.display();
}}
Output:
import java.util.*;
class GenericStack<T> {
Scanner scan = new Scanner(System.in);
int top = -1;
int size;
T t;
List<T> Stack;
GenericStack(int size) {
Stack = new ArrayList<T>(size);
this.size = size;
}
void push(T item) {
// T item = (T) scan.next();
top++;
Stack.add(top, item);
}
public T pop() {
if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
return Stack.remove(top--);
}
public T peek() {
if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
return Stack.get(top);
}
public void display() {
System.out.println("Stack elements are:");
12202040501019 Dharmik Rabadiya
if (top == -1) {
throw new IllegalStateException("Stack is Empty");
}
for (int i = top; i >= 0; i--) {
System.out.println("Stack[" + i + "] : " + Stack.get(i));
}
}
}
public class StackMain {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int ch;
GenericStack<Character> stack = new GenericStack<>(5);
do {
System.out.println("1.Push\n2.PoP\n3.Peek\n4.Display Stack\n5.Exit");
ch = scan.nextInt();
switch (ch) {
case 1:
stack.push('A');
stack.push('B');
stack.push('C');
stack.push('D');
break;
case 2:
System.out.println("Poped Element is : " + stack.pop());
break;
case 3:
System.out.println("Top Element is : " + stack.peek());
break;
case 4:
12202040501019 Dharmik Rabadiya
stack.display();
break;
case 5:
System.exit(0);
break;
} } while (ch != 5);
}}
Output:
Code:
import java.util.*;
class Book implements Comparable<Book> {
String bookTitle;
String bookAuthor;
String bookPublisher;
int bookID;
public Book(String bookTitle, String bookAuthor, String bookPublisher, int bookID) {
this.bookTitle = bookTitle;
this.bookAuthor = bookAuthor;
this.bookPublisher = bookPublisher;
this.bookID = bookID; }
@Override
public String toString() {
return ( "Book [ bookID=" +bookID +", bookTitle=" +bookTitle +", bookAuthor=" +
bookAuthor +", bookPublisher=" + bookPublisher + "]" ); }
@Override
public int compareTo(Book o) {
return this.bookTitle.compareTo(o.bookTitle);
}}
public class BooksMain {
Scanner s= new Scanner(System.in);
public static void main(String[] args) {
ArrayList<Book> bookList = new ArrayList<>();
int ch;
bookList.add(new Book("Java Programming", " HG ", "ABC", 53));
bookList.add(new Book("Technical writing", " CZ ", "XYZ", 24));
bookList.add(new Book("Computer Organization", " SV ", "PQR", 91));
for (Book book : bookList) { System.out.println(book); }
do {
System.out.println("\n1.Sort Using Comparator\n2.Sort Using Comparable\n3.Exit");
12202040501019 Dharmik Rabadiya
ch = s.nextInt();
switch (ch) {
case 1: System.out.println(“Sorting Using Comparator");
Comparator<Book> cmp = new Comparator<Book>() {
@Override
public int compare(Book i, Book j) {
if (i.bookID > j.bookID) return 1;
else return -1; } };
Collections.sort(bookList, cmp);
for (Book book : bookList) { System.out.println(book); }
break;
case 2: System.out.println(“Sorting Using Comparable ");
Collections.sort(bookList);
for (Book book : bookList) { System.out.println(book); }
break; }
} while (ch != 3); } }
Output:
Practical 7
Write a program for creating a Bank class, which is used to manage
the bank account of customers. Class has two methods, Deposit ()
12202040501019 Dharmik Rabadiya
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.
Code:
import java.lang.System;
import java.util.*;
class NotEnoughMoneyExecption extends Exception {
public NotEnoughMoneyExecption(String s) {
super(s);
}}
class bankAccount {
double balance, newDeposit, withdraw;
String accountType, name;
Scanner scan = new Scanner(System.in);
public static void exit() {
exit();
}
void createAccount() {
System.out.println("Create New Account");
System.out.print("Enter Your Full Name : ");
name = scan.nextLine();
System.out.print("\nEnter Your Account Type (Saving/Current): ");
accountType = scan.next();
System.out.print("\nEnter Your Initial Balance : ");
balance = scan.nextInt(); }
void deposite() {
System.out.println("Your Current Account Balance is : " + balance);
System.out.print("\nEnter The Amount You Want To Deposite : ");
12202040501019 Dharmik Rabadiya
newDeposit = scan.nextInt();
balance = newDeposit + balance;
System.out.println("Your Account Balance after Depositing " + newDeposit + "Rs. is
"+ balance);
}
void withdraw() {
System.out.println("Money Withdrawl Window");
System.out.println("Your Current Account Balance is : " + balance);
System.out.print("\nEnter The Amount You Want To Withdraw : ");
withdraw = scan.nextInt();
try {
if (balance < withdraw) {
throw new ArithmeticException("Amount Exceede Current Balance");
}
balance = balance - withdraw;
System.out.println("Your Account Balance after Widthrawing " +withdraw +" RS is " +
balance);
try {
if (balance < 500) {
throw new NotEnoughMoneyExecption("Minimum Balance is 500 \nYour Balance is
Below 500");
}
} catch (NotEnoughMoneyExecption e) {
System.out.println(e);
System.exit(0);
} } catch (ArithmeticException e) {
System.out.println(e);
System.exit(0);} }
void display(int ac) {
System.out.println("\nAccount Information");
System.out.println("Name : " + name);
12202040501019 Dharmik Rabadiya
case 4:
System.out.println("Enter Your Account Number : ");
ac=scan.nextInt();
bank[ac].display(ac);break;
}
}while(ch!=5);
}}
Output:
int n = scan.nextInt();
ExceptionClass exception = new ExceptionClass(n);
try {
if (n == 0) {
throw new ArithmeticException("Value of N is Zero");
}
try {
exception.readElements();
exception.display();
} catch (NegativeArraySizeException ne) {
System.out.println(ne);
}
} catch (ArithmeticException ae) {
System.out.println(ae);
}}}
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.
Code:
12202040501019 Dharmik Rabadiya
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);
12202040501019 Dharmik Rabadiya
Output:
12202040501019 Dharmik Rabadiya
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;
12202040501019 Dharmik Rabadiya
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");
12202040501019 Dharmik Rabadiya
consume.start(); }
public void run() {
while (true) {
item.get();
try {
Thread.sleep(1000);
} catch (Exception e) {}
}}}
class QueueMain {
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
12202040501019 Dharmik Rabadiya
}
System.out.println("LinkedHashMap");
LinkedHashMap<Integer, String> lhm = new LinkedHashMap<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter Name %d :", i);
lhm.put(i, scan.next());
}
System.out.println("Displaying Linked list");
System.out.printf("Value of LinkedList ");
for (Map.Entry m : lhm.entrySet()) {
System.out.println(m);
}
System.out.println("TreeMap");
TreeMap<Object, Object> treeMap = new TreeMap<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter Name %d :", i);
treeMap.put(i, scan.next());
}
System.out.println("Displaying Linked list");
System.out.printf("Value of Map ");
System.out.println(treeMap);
}
}
Output:
12202040501019 Dharmik Rabadiya
import java.io.*;
import java.util.*;
public class P0902 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
System.out.println("Array List");
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :", i);
arr.add(scan.next());
}
System.out.println("Displaying Array list");
System.out.printf("Value of ArrayList ");
System.out.println(arr);
Collections.sort(arr);
System.out.println("Sorted Array " + arr);
System.out.println("Linked List");
LinkedList<String> ll = new LinkedList<>();
for (int i = 0; i < 5; i++) {
System.out.printf("Enter %d :\n", i);
ll.add(scan.next());
}
Collections.sort(ll);
Iterator<String> itr = ll.iterator();
System.out.println("Displaying Linked list");
System.out.printf("Value of LinkedList\n");
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
12202040501019 Dharmik Rabadiya
Output:
Practical 10
12202040501019 Dharmik Rabadiya
Output:
Code:
import java.io.*;
import java.util.Scanner;
//Write a program to print it self.
class Readitself{
public static void main(String[] args)
throws IOException,FileNotFoundException {
FileReader fileReader = new FileReader("Readitself.java"); //filename
Scanner scan = new Scanner(fileReader);
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
scan.close();
}
}
Output:
Code:
import java.io.*;
public class DirectoryMain {
public static void main(String[] args) throws IOException {
File file = new File("D:\12202080501083_shrey");
if (file.isDirectory())
{
System.out.println("Directory Name : " + file.getPath());
String directoryList[] = file.list();
for (int i = 0; i < directoryList.length; i++) {
File list = new File(file.getPath() + "//" + directoryList[i]);
if (list.isDirectory()) {
System.out.println(directoryList[i] + " is Directory.");
} else if (list.isFile()) {
System.out.println(directoryList[i] + " is File.");
}}}}
}
Code:
Practical 11
12202040501019 Dharmik Rabadiya
in.close();
}
public static void main(String[] args) throws Exception {
ServerClient sc = new ServerClient();
Client c = sc.new Client();
c.clientConnect();
}
public static void delay() throws Exception {
Thread.sleep(700);
}}}
Output:
From Client side:
Practical 12
12202040501019 Dharmik Rabadiya
frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.blue));
frame.setBounds(450, 200, 0, 0);
frame.setBackground(Color.red);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(420, 420);
frame.setLayout(null);
// frame.add(myButton);
frame.setVisible(true); }
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton) {
frame.dispose(); }
if (e.getSource() == calculateButton) {
String amountFielString = amountField.getText().toString();
String intresstRateString = intrestRateField.getText().toString();
String yearString = yearField.getText().toString();
double amount = Integer.parseInt(String.valueOf(amountFielString));
int year = Integer.parseInt(String.valueOf(yearString));
double intrestRate = Integer.parseInt(String.valueOf(intresstRateString));
double futureValue = (amount * (Math.pow(1 + (intrestRate / 100), year)));
futureValueField.setText(Double.toString(futureValue)); } } }
Output:
12202040501019 Dharmik Rabadiya
2 Write a program which fills the rectangle with the selected color
when the button is pressed.
import java.awt.*;
import java.awt.Color.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.imageio.plugins.tiff.GeoTIFFTagSet;
import javax.swing.*;
class frame extends JFrame implements ActionListener {
JButton red, green, blue;
JPanel PanelRight = new JPanel();
JPanel PanelLeft = new JPanel();
frame() {
PanelLeft.setBounds(0, 0, 200, 200);
PanelLeft.setBackground(Color.green);
PanelLeft.setLayout(null);
PanelRight.setBounds(210, 0, 200, 200);
// PanelRight.setBackground(Color.green);
red = new JButton("Red");
green = new JButton("green");
blue = new JButton("blue");
red.setBounds(20,30,75,25);
blue.setBounds(20,60,75,25);
green.setBounds(20,90,75,25);
blue.setFocusable(true);
setLayout(null);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
12202040501019 Dharmik Rabadiya
add(PanelLeft);
add(PanelRight);
PanelLeft.add(red);
PanelLeft.add(blue);
PanelLeft.add(green);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == red) {
PanelRight.setBackground(Color.red);
} else if (e.getSource() == blue) {
PanelRight.setBackground(Color.blue);
} else if (e.getSource() == green) {
PanelRight.setBackground(Color.green);
}}}
public class ButtonMain {
public static void main(String[] args) {
frame frame = new frame();
frame.setTitle("I Am JFrame");
frame.setSize(410, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
Output: