Vaish college of engineering
Practical File
Programming In Java
Submitted By:- Submitted To:-
Shubh Agarwal Mrs Annu
20/CSE/151 Asstt. Professor
Univ. Roll no. 9049376 (CSE Department)
Sr.no
Name of program Teacher’s Remarks
1
Write a java program to Demonstrate Type Casting.
2
Write a java program to implement stack and queue.
3
Write a java program to create a Simple class to find out the
Area and perimeter of a rectangle and box using super and
this keyword.
4
Write a java program Convert the content of a given String
into the upper case content of the same string.
5
Write a java program for Producer-Consumer Problem Using
Inter-thread Communication
6
Write a java Program for Exception handling and also make
use of all the5 exception keywords.
7
a) Write a java program to develop an applet that displays a
simple message.
b) Develop an Applet that receives an integer in one text field
& compute its factorial value & returns it in another text field
when the button “Compute” is clicked.
8
Write a java program for multiple inheritances using extend
and implement keywords.
9
Write a java program to show dynamic polymorphism.
10
Write a java program to develop a calculator with the help of
AWT/Swing with event handling.
Program - 1
AIM: java program to Demonstrate Type Casting.
INPUT:
public static void main(String[] args) {
System.out.println("Demonstration of Type casting:"); short Short=20;
int shorToInt=Short;
long intToLong=shorToInt;
float longToFloat=intToLong;
double floatToDouble=longToFloat;
System.out.println("Original\tConverted\tValue:");System.out.println("S
hort\t\tShort\t\t"+Short+
}}
"\nShort\t\tInteger\t\t"+shorToInt+
"\nInteger\t\tLong\t\t"+intToLong+"\nLong\t\tFloat\t\t"+longToFloat+
"\nFloat\t\tDouble\t\t"+floatToDouble+
"\nDouble\t\tFloat\t\t"+(float)floatToDouble+"\nFloat\t\tLong\t\t"+(long)
longToFloat+
"\nLong\t\tInteger\t\t"+(int)intToLong+
"\nInteger\t\tShort\t\t"+(short)shorToInt+"\nShort\t\tBite\t\t"+(byte)shor
TInt
);
Output:
Program 2
AIM: Implement stack and queue.
INPUT:
// Java code for stack implementation
import java.io.*;
import java.util.*;
class Test
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
for(int i = 0; i < 5; i++)
stack.push(i);
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
System.out.println("Pop Operation:");
for(int i = 0; i < 5; i++)
Integer y = (Integer) stack.pop();
System.out.println(y);
// Displaying element on the top of the stack
static void stack_peek(Stack<Integer> stack)
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
Integer pos = (Integer) stack.search(element);
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
public static void main (String[] args)
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
Output:
AIM: Java program to demonstrate a Queue
INPUT:
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args)
Queue<Integer> q
= new LinkedList<>();
// Adds elements {0, 1, 2, 3, 4} to
// the queue
for (int i = 0; i < 5; i++)
q.add(i);
// Display contents of the queue.
System.out.println("Elements of queue "
+ q);
// To remove the head of queue.
int removedele = q.remove();
System.out.println("removed element-"
+ removedele);
System.out.println(q);
// To view the head of queue
int head = q.peek();
System.out.println("head of queue-"
+ head);
// Rest all methods of collection
// interface like size and contains
// can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-"
+ size);
Output:
Program – 3
Program To Find Out Area And Perimeter Of Rectangle And Box.
INPUT:
import java.util.Scanner;
class Rectangle{ int length;
int breadth;
Scanner input=new Scanner(System.in); public Rectangle(){};
public Rectangle(int length,int breadth){
this.length = length;
this.breadth = breadth; }
public int getArea(){
return length*breadth; }
public int getPerimeter(){ return 2*(length+breadth);
}}
class Box extends Rectangle{
int height;
public Box(int length,int breadth){
super(length, breadth);
this.height=0; }
public Box(int length,int breadth,int height){ super(length,breadth); this.height=height;
public int getAreaBox() {
return 2*(super.getArea() +length*height+breadth*height);
}
public int getPerimeterBox(){
return 4*(length+height+breadth);
Output:
Program - 4
AIM: Convert given String into the upper case
INPUT:
public class canva {
public static void main(String[] args) {
String str1 = "Generic Text";
StringBuffer newStr = new StringBuffer(str1); System.out.println("String Before
Converting:"+str1); for(int i=0;i<str1.length();i++){
if(Character.isLowerCase(str1.charAt(i))) { newStr.setCharAt(i,
Character.toUpperCase(str1.charAt(i))); }
else if(Character.isUpperCase(str1.charAt(i))) { newStr.setCharAt(i,
Character.toLowerCase(str1.charAt(i)));
}}
System.out.println("string after case conversion : " + newStr);
Output:
Program - 5
AIM: Java program to implement the solution of
producer-consumer problem.
INPUT:
import java. util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumer (removes items).
public static class PC {
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();
// to retrieve the first job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
Output:
:
Program - 6
AIM: Write a java Program for Exception handling and also make
use of all the 5 exception keywords.
INPUT:
class Alpha
public static int division(int x , int y )
{ ArithmeticException temp =null;
int r=0;
System.out.println(" with in div function...");
try
r=x/y;
} catch(ArithmeticException ee)
System.out.println("unable to divide");
temp = ee ;
throw ee;
finally
System.out.println(" in finaaly ");
return 670;
// System.out.println(" resuming div task...");
}
}
class DemoEx5
public static void main(String args[]) throws ArithmeticException
int res=0;
try
res= Alpha.division( 20 , 0 );
System.out.println(" res..." + res);
}catch(ArithmeticException ee)
System.out.println(" unable to continue as division is not giving me result....");
// ee.printStackTrace();
System.out.println(" exiting from main...");
Output:
Program - 7
AIM: Write a java program to develop an applet that displays a
simple message.
INPUT:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet{ public void paint(Graphics g){
g.drawString("Hello Java",10, 100);
output:
AIM: Develop an Applet that receives an integer in one text field &
computes its factorial value & returns it in another text field when
the button “Compute” is clicked.
INPUT:
import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
public class Fact extends Applet implements ActionListener{ String str;
Button b0;
TextField t1,t2;
Label l1;
public void init(){
Panel p = new Panel();
p.setLayout(new GridLayout());
add(new Label("enter any integer value"));
add(t1= new TextField(20));
add(new Label("Factorial value is : "));
add(t2= new TextField(20));
add(b0 = new Button ("compute")); b0.addActionListener(this);
public void actionPerformed(ActionEvent e){
int i, n, f=1;
n= Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f= f*i;
t2.setText(String.valueOf(f));
repaint();
}}
output:
Program - 8
AIM: Write a java program for multiple inheritance using extend
and implement keyword.
INPUT:
Using implement keyword
interface AnimalEat {
void eat();
interface AnimalTravel {
void travel();
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
public void travel() {
System.out.println("Animal is travelling");
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel(); }}
Output:
Animal is eating
Animal is travelling
Using extend keyword
Multiple inheritance in java is the capability of creating a single class with multiple superclasses.
Unlike some other popular object oriented programming languages like C++, java doesn't
provide support for multiple inheritances in classes
// Java Program to Illustrate Unsupportance of
// Multiple Inheritance
import java.io.*;
// Class 1
// A Grandparent class in diamond
class GrandParent {
void fun() {
// Print statement to be executed when this method is called
System.out.println("Grandparent");
// Class 2
// First Parent class
class Parent1 extends GrandParent {
void fun() {
// Print statement to be executed when this method is called
System.out.println("Parent1");
}
// Class 3
// Second Parent Class
class Parent2 extends GrandParent {
void fun() {
// Print statement to be executed when this method is called
System.out.println("Parent2");
// Class 4
// Inheriting from multiple classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {
// Creating object of this class i main() method
Test t = new Test();
// Now calling fun() method from its parent classes
// which will throw compilation error
t.fun();
Output:
Program - 9
AIM: Write a java program to show dynamic polymorphism.
Input:
class Bank{
int getRateOfInterest(){
return 0;}
class SBI extends Bank{
int getRateOfInterest()
return 8; }}
class ICICI extends Bank{ int getRateOfInterest(){
return 7; }}
class AXIS extends Bank{ int GetRateOfInterest(){
return 9; }}
public class Main {
public static void main(String[] args) {
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS(); System.out.println("SBI RATe of interest: " +
s.getRateOfInterest());
System.out.println("ICICI RATe of interest: " +
i.getRateOfInterest());
System.out.println("AXIS RATe of interest: " +
a.getRateOfInterest());} }
output:
Program - 10
AIM: Write a java program to develop a calculator with the help of
AWT/Swing with event handling.
INPUT:
// Java program to create a simple calculator
// with basic +, -, /, * using java swing elements
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// store operator and operands
String s0, s1, s2;
// default constructor
calculator()
{
s0 = s1 = s2 = "";
// main function
public static void main(String args[])
// create a frame
f = new JFrame("calculator");
try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e) {
System.err.println(e.getMessage());
// create a object of class
calculator c = new calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq,
beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
// add action listeners
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
// add elements to panel
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
// set Background of panel
p.setBackground(Color.blue);
// add panel to frame
f.add(p);
f.setSize(200, 220);
f.show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
// if the value is a number
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
// set the value of text
l.setText(s0 + s1 + s2);
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
else if (s.charAt(0) == '=') {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));
// set the value of text
l.setText(s0 + s1 + s2 + "=" + te);
// convert it to string
s0 = Double.toString(te);
s1 = s2 = "";
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) +
Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) -
Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) /
Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) *
Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
}
output: