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

Java Pratham Kakkar

The document is a practical file submitted by Pratham Kakkar for the subject Java Programming Lab. It contains 22 experiments conducted on various Java programming concepts like variables, operators, inheritance, exceptions, files etc. Each experiment contains the aim, theory, program code and output. The file also includes an index listing the experiments.

Uploaded by

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

Java Pratham Kakkar

The document is a practical file submitted by Pratham Kakkar for the subject Java Programming Lab. It contains 22 experiments conducted on various Java programming concepts like variables, operators, inheritance, exceptions, files etc. Each experiment contains the aim, theory, program code and output. The file also includes an index listing the experiments.

Uploaded by

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

PRACTICAL FILE

OF

Java Programming Lab


(Paper code: ETCS-357)

Submitted to: Submitted by:


Mr. Vedprakash Sharma Pratham Kakkar
Assistant Professor 09115603120
IT Department. T-7 IT

DR. AKHILESH DAS GUPTA INSTITUTE OF TECHNOLOGY


AND MANAGEMENT
NEW DELHI

Pratham Kakkar
Roll no:09115603120
INDEX

S.No. Experiment Date Remarks T. Sign


1. Write a program in java to perform addition of 2
numbers using command Line
Argument.
2. Write a program in to implement different types of
variables in Java (local, static and
instance variables).
3. Write a program in java to Perform basic arithmetic
calculations using switch case.
4. Write a program in java to perform sorting.
5. Create a java program to implement stack and
queue concept.
6. Write a program in java to perform single level
inheritance.
7. Write a program in java to perform Multilevel
inheritance.
8. Write a java package to show dynamic
polymorphism and interfaces.
9. Write a program in java to perform constructor
overloading.
10. Create a customized exception and also make use
of all the 5 exception keywords.
11. Write a program to show use of customized
packages.
12. Write a program to show that String is immutable
and String buffer is mutable.
13. Write a program to perform all String operations.
14. Write a program to check String is Palindrome or
not.
15. Develop an analog clock using applet.
16. (a) Write a program to print table of 2 numbers
without using synchronization using
multithreading.
(b) Write a program to print table of 2 numbers
using synchronization using
multithreading.
17. Write a java program to show multithreaded
producer and consumer application.
18. Write a program to perform event handling in Java.
Create a GUI using AWT that
performs arithmetic operations.

Pratham Kakkar
Roll no:09115603120
19. Convert the content of a given file into the
uppercase content of the same file.
20. Write a program to perform operations such as
insertion, deletion, updation and
retrieval of records on Employee database using
JDBC.
21. Develop a scientific calculator using swings.
22. Create an editor like MS-word using swings.

Pratham Kakkar
Roll no:09115603120
Experiment No. 1

Aim: Write a program to perform addition of two numbers using command line.

Theory: In Java, finding the sum of two or more numbers is very easy. First,
declare and initialize two variables to be added. Another variable to store the sum
of numbers. Apply mathematical operator (+) between the declared variable and
store the result. The following program calculates and prints the sum of two
numbers.

Program:

public class SumOfNumbers1


{
public static void main(String args[])
{
int n1 = 225, n2 = 115, sum;
sum = n1 + n2;
System.out.println("The sum is: "+sum);
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 2

Aim: Write a program to implement different types of variables in java.

Theory: 1) Local Variable


A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.

Program:

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}

Pratham Kakkar
Roll no:09115603120
Experiment No. 3

Aim: Write a program to implement basic arithmetic calculation using switch.

Theory: Switch statements are basically a combination of if-else statement.

Program: import java.util.Scanner;

class Main {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
Scanner input = new Scanner(System.in);

System.out.println("Choose an operator: +, -, *, or /");


operator = input.next().charAt(0);
System.out.println("Enter first number");
number1 = input.nextDouble();

System.out.println("Enter second number");


number2 = input.nextDouble();

switch (operator) {
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);

Pratham Kakkar
Roll no:09115603120
break;

default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 4

Aim: Write a program in java to perform sorting.

Theory: Sorting an array means to arrange the elements in the array in a certain
order. Various algorithms have been designed that sort the array using different
methods. Some of these sorts are more useful than the others in certain situations.

Program:
import java.util.Arrays;
public class program {

public static void main(String[] args)


{
int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
Arrays.sort(arr);

System.out.print("Modified arr[] : %s",


Arrays.toString(arr));
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 5

Aim: Write a program in java to implement stack and queue concept.

Theory: Stack- Stack is a linear data structure which follows a particular order in
which the operations are performed. The order may be LIFO(Last In First Out) or
FILO(First In Last Out).

Queue - A Queue is a linear structure which follows a particular order in which the
operations are performed. The order is First In First Out (FIFO).

Program:
Stack
class Stack {
static final int MAX = 1000;
int top;
int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}

boolean push(int x)
{
if (top >= (MAX - 1)) {
System.out.println("Stack Overflow");
return false;
}
else {
a[++top] = x;
System.out.println(x + " pushed into stack \n");
return true;
}

Pratham Kakkar
Roll no:09115603120
}

int pop()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
}
}

int peek()
{
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top];
return x;
}
}

void print(){
for(int i = top;i>-1;i--){
System.out.print(" "+ a[i]);
}
}
}
class Main {
public static void main(String args[])
{
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop() + " Popped from stack");
Pratham Kakkar
Roll no:09115603120
System.out.println("Top element is :" + s.peek());
System.out.print("Elements present in stack :");
s.print();
}
}

Queue
class Queue {
private static int front, rear, capacity;
private static int queue[];

Queue(int c)
{
front = rear = 0;
capacity = c;
queue = new int[capacity];
}
static void queueEnqueue(int data)
{
if (capacity == rear) {
System.out.printf("\nQueue is full\n");
return;
}
else {
queue[rear] = data;
rear++;
}
return;
}
static void queueDequeue()
{
if (front == rear) {
System.out.printf("\nQueue is empty\n");
return;
}
else {
for (int i = 0; i< rear - 1; i++) {
queue[i] = queue[i + 1];
}
if (rear < capacity)
Pratham Kakkar
Roll no:09115603120
queue[rear] = 0;
rear--;
}
return;
}
static void queueDisplay()
{
int i;
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
for (i = front; i< rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
return;
}
static void queueFront()
{
if (front == rear) {
System.out.printf("\nQueue is Empty\n");
return;
}
System.out.printf("\nFront Element is: %d", queue[front]);
return;
}
}

public class StaticQueueinjava {


public static void main(String[] args)
{
Queue q = new Queue(4);
q.queueDisplay();
q.queueEnqueue(20);
q.queueEnqueue(30);
q.queueEnqueue(40);
q.queueEnqueue(50);
q.queueDisplay();
q.queueEnqueue(60);
q.queueDisplay();
Pratham Kakkar
Roll no:09115603120
q.queueDequeue();
q.queueDequeue();
System.out.printf("\n\nafter two node deletion\n\n");
q.queueDisplay();
q.queueFront();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 6

Aim: Write a program in java to perform single level inheritance.

Theory: When a class inherits another class, it is known as a single inheritance.

Program:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}

Output:
weeping...
barking...
eating...

Pratham Kakkar
Roll no:09115603120
Experiment No. 7

Aim: Write a program in java to perform Multilevel inheritance.

Theory: A class inherits properties from a class which again has inherits
properties.

Program:
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 8

Aim: Write a java package to show dynamic polymorphism and interfaces.

Theory:

Program for Interfaces.:


class A{
int a=5;
void display(){
System.out.println("Super Class");
}
}
interface C{
int c=15;
void display();
}
class B extends A implements C {
int b=10;
public void display(){
super.display();
System.out.println("Interface");
}
public static void main(String[] args){
B object=new B();
System.out.println(object.a);
System.out.println(object.b);
System.out.println(object.c);
object.display();
}
}
Output:

Pratham Kakkar
Roll no:09115603120
Program for Polymorphism:
class A{
public void display(){
System.out.println("Printing from the Super Class");
}
}
class B extends A{
public void display(){
super.display();
System.out.println("Printing from the Sub Class");
}
public static void main(String[] args){
B obj=new B();
obj.display();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 9

Aim: Write a program in java to perform constructor overloading.

Theory:

Program:
class overloading {
int a;
int b;
int c;
public overloading(int a, int b, int c){
this.a=a;
this.b=b;
this.c=c;
}
public overloading(int a, int b){
this.a=a;
this.b=b;
this.c=0;
}
public overloading(){
this.a=0;
this.b=0;
this.c=0;
}
public void display(){
System.out.println("a = "+a+"\tb = "+b+"\tc = "+c);
}
public static void main(String[] args){
overloading first= new overloading(1,2,3);
overloading second=new overloading(1,2);
overloading third=new overloading();
System.out.println("Values from first object : ");
first.display();
System.out.println("============================================
================================");
System.out.println("Values from second object : ");

Pratham Kakkar
Roll no:09115603120
second.display();
System.out.println("============================================
================================");
System.out.println("Values from third object : ");
third.display();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 10

Aim: Create a customized exception and also make use of all the 5 exception
keywords.

Theory:

Program:
class myException extends Exception{
public myException(String message){
super(message);
}
}
public class main{
static void check(int number) throws myException{
if(number<0 || number>99)
throw new myException("Entered Number is not a whole
number(<100).");
else
System.out.println("You've entered a whole number.");
}
public static void main(String[] args)
{
try{
check(Integer.valueOf(args[0]));
}
catch(myException e){
System.out.println("Exception Caught" + e);
}
finally{
System.out.println("This is how we managed the custom Exception :)
");
}
}
}

Pratham Kakkar
Roll no:09115603120
Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 11

Aim: Write a program to show use of customized packages.

Theory:

Program:
package IPU;
public class ADGITM{
int numberOfConsents;
int totalStudents;
int numberOfRegularStudents;
boolean collegeOpen;
public ADGITM(int a, int b, int d){
numberOfConsents = a;
totalStudents = b;
numberOfRegularStudents = d;
collegeOpen=false;
}
public void showConsentOfStudents(){
System.out.println("Total Consents : "+ numberOfConsents);
System.out.println("Total Students : "+ totalStudents);
System.out.println("Total Number Of Students who attend classes
regularly : "+ numberOfRegularStudents);
System.out.println("Are Colleges Open? : "+ collegeOpen);
System.out.println("OOPS!! College authorities don't want it open.
YET!!!!!!\n :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :( :(
:( :( ");
}
}
package IPU;
public class MAIT{
int numberOfConsents;
int totalStudents;
int numberOfRegularStudents;
boolean collegeOpen;
public MAIT(int a, int b, int d){
numberOfConsents = a;
totalStudents = b;

Pratham Kakkar
Roll no:09115603120
numberOfRegularStudents = d;
if(numberOfConsents > totalStudents/2)
collegeOpen = true;
else
collegeOpen = false;
}
public void showConsentOfStudents(){
System.out.println("Total Consents : "+ numberOfConsents);
System.out.println("Total Students : "+ totalStudents);
System.out.println("Total Number Of Students who attend classes
regularly : "+ numberOfRegularStudents);
System.out.println("Are Colleges Open? : "+ collegeOpen);
if(collegeOpen)
System.out.println("YAYY!!!!!!\n :) :) :) :) :) :) :) :) :) :) :) :) :)
:) :) :) :) :) :) :)");
}
}
Code for Main Class:
import IPU.*;
class College
{
public static void main(String[] args){
ADGITM niec = new ADGITM(38, 70, 35);
MAIT mait= new MAIT(40, 70, 50);
System.out.println("For ADGITM : ");
niec.showConsentOfStudents();
System.out.println("\n\nFor MAIT : ");
mait.showConsentOfStudents();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 12

Aim: Write a program to show that String is immutable and String buffer is
mutable.

Theory: A String is an unavoidable type of variable while writing any application


program. String references are used to store various attributes like username,
password, etc. In Java, String objects are immutable. Immutable simply means
unmodifiable or unchangeable.

Program:
For immutable
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s);
}
}

Output:
Sachin

For mutable
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Output:
Sachin Tendulkar

Pratham Kakkar
Roll no:09115603120
Experiment No. 13

Aim: Write a program to perform all String operations.

Theory:

Program:
import java.util.*;
class StringOperation
{
public static void main(String[] args)
{
String first="",second="";
Scanner sc=new Scanner(System.in);
System.out.println("String Operation");
System.out.println();
System.out.print("Enter the first Sting: ");
first=sc.nextLine();
System.out.print("Enter the second Sting: ");
second=sc.nextLine();
System.out.println("The strings are: "+first+" , "+second);
System.out.println("The length of the first string is :"+first.length());
System.out.println("The length of the second string is
:"+second.length());
System.out.println("The concatenation of first and second string is
:"+first.concat(" "+second));
System.out.println("The first character of " +first+" is: "+first.charAt(0));
System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());
System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());
System.out.print("Enter the occurance of a character in "+first+" : ");
String str=sc.next();
char c=str.charAt(0);
System.out.println("The "+c+" occurs at position " + first.indexOf(c)+ " in
" + first);
System.out.println("The substring of "+first+" starting from index 3 and
ending at 6 is: " + first.substring(3,7));
System.out.println("Replacing 'a' with 'o' in "+first+" is:
"+first.replace('a','o'));
boolean check=first.equals(second);

Pratham Kakkar
Roll no:09115603120
if(!check)
System.out.println(first + " and " + second + " are not same.");
else
System.out.println(first + " and " + second + " are same.");
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 14

Aim: Write a program to check String is Palindrome or not.

Theory:

Program:
classpractice {
publicstaticvoidmain(String[] args) {

String str="racecar", reverseStr="";

intstrLength=str.length();

for (inti= (strLength-1); i>=0; --i) {


reverseStr=reverseStr+str.charAt(i);
}

if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
System.out.println(str +" is a Palindrome");
} else {
System.out.println(str +"is Not a Palindrome");
}
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 15

Aim: Develop an analog clock using applet.

Theory:

Program:
import java.applet.Applet;
import java.awt.*;
import java.util.*;
public class analogClock extends Applet {
@Override
public void init()
{
// Applet window size & color
this.setSize(new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread() {
@Override
public void run()
{
while (true) {
repaint();
delayAnimation();
}
}
}.start();
}

// Animating the applet


private void delayAnimation()
{
try {

// Animation delay is 1000 milliseconds


Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();

Pratham Kakkar
Roll no:09115603120
}
}

// Paint the applet


@Override
public void paint(Graphics g)
{
// Get the system time
Calendar time = Calendar.getInstance();

int hour = time.get(Calendar.HOUR_OF_DAY);


int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);

// 12 hour format
if (hour > 12) {
hour -= 12;
}

// Draw clock body center at (400, 200)


g.setColor(Color.white);
g.fillOval(300, 100, 200, 200);

// Labeling
g.setColor(Color.black);
g.drawString("12", 390, 120);
g.drawString("9", 310, 200);
g.drawString("6", 400, 290);
g.drawString("3", 480, 200);

// Declaring variables to be used


double angle;
int x, y;

// Second hand's angle in Radian


angle = Math.toRadians((15 - second) * 6);

// Position of the second hand


// with length 100 unit
x = (int)(Math.cos(angle) * 100);
Pratham Kakkar
Roll no:09115603120
y = (int)(Math.sin(angle) * 100);

// Red color second hand


g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);

// Minute hand's angle in Radian


angle = Math.toRadians((15 - minute) * 6);
// Position of the minute hand
// with length 80 unit
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);
// blue color Minute hand
g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);
// Hour hand's angle in Radian
angle = Math.toRadians((15 - (hour * 5)) * 6);
// Position of the hour hand
// with length 50 unit
x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);
// Black color hour hand
g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 16

Aim: (a) Write a program to print table of 2 numbers without using


synchronization using multithreading.
(b) Write a program to print table of 2 numbers using synchronization using
multithreading.

Theory:

Program: (a)
class Table
{
/*synchronized*/ void printTable(int n)
{
//synchronized(this)
{
for(int i=1;i<=10;i++)
{
System.out.println(+n+"*"+i+"="+(n*i));
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}

class Mythread1 extends Thread


{
Table t;
Mythread1(Table t)
{
this.t=t;
}

Pratham Kakkar
Roll no:09115603120
public void run()
{
t.printTable(2);
}
}

class Mythread2 extends Thread


{
Table t;
Mythread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(3);
}
}

class ThreadWithoutSync
{
public static void main(String args[])
{
Table obj = new Table();
Mythread1 th1 = new Mythread1(obj);
Mythread2 th2 = new Mythread2(obj);
th1.start();
th2.start();
}
}

Pratham Kakkar
Roll no:09115603120
Output:

Program: (a)

class Table
{
synchronized void printTable(int n)
{
//synchronized(this)
{
for(int i=1;i<=10;i++)
{
System.out.println(+n+"*"+i+"="+(n*i));
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

Pratham Kakkar
Roll no:09115603120
}

class Mythread1 extends Thread


{
Table t;
Mythread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(2);
}
}

class Mythread2 extends Thread


{
Table t;
Mythread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(3);
}
}

class ThreadWithoutSync
{
public static void main(String args[])
{
Table obj = new Table();
Mythread1 th1 = new Mythread1(obj);
Mythread2 th2 = new Mythread2(obj);
th1.start();
th2.start();
}
}
Pratham Kakkar
Roll no:09115603120
Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 17

Aim: Write a java program to show multithreaded producer and consumer


application.

Theory:

Program:
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();

Thread t1 = new Thread(new Runnable() {


@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

Pratham Kakkar
Roll no:09115603120
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{

while (list.size() == capacity)


wait();

System.out.println("Producer produced-"
+ value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);
notify();
Thread.sleep(1000);
Pratham Kakkar
Roll no:09115603120
}
}
}
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 18

Aim: Write a program to perform event handling in Java. Create a GUI using
AWT that performs arithmetic operations.

Theory: Java AWT (Abstract Window Toolkit) is an API to develop Graphical


User Interface (GUI) or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).

Program:
#For Event Handling
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){

Pratham Kakkar
Roll no:09115603120
new AEvent();
}
}

Output:

Program:
#For Arithmetic Operations
import java.awt.*;
public class AWTExample1 extends Frame {
AWTExample1() {
Button b = new Button("Click Me!!");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
}
public static void main(String args[]) {

Pratham Kakkar
Roll no:09115603120
AWTExample1 f = new AWTExample1();
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 19

Aim: Convert the content of a given file into the uppercase content of the same
file.

Theory:

Program: public class Exercise30 {

public static void main(String[] args)


{
String str = "The Quick BroWn FoX!";

// Convert the above string to all uppercase.


String upper_str = str.toUpperCase();

// Display the two strings for comparison.


System.out.println("Original String: " + str);
System.out.println("String in uppercase: " + upper_str);
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 20

Aim: Write a program to perform operations such as insertion, deletion, updation


and retrieval of records on Employee database using JDBC.

Theory:

Program:
import java.sql.*;
class EmployeeRecord
{
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
public static final String DBUSER = "local";
public static final String DBPASS = "test";
public static void main(String args[])
{
try
{
//Loading the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Cretae the connection object
Connection con = DriverManager.getConnection(DBURL, DBUSER,
DBPASS);
//Insert the record
String sql = "INSERT INTO emp (emp_id, empname, email, city)
VALUES (?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 100);
statement.setString(2, "Prashant");
statement.setString(3, "[email protected]");
statement.setString(4, "Pune");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0)
{
System.out.println("A new employee was inserted successfully!\n");
}
// Display the record
String sql1 = "SELECT * FROM Emp";

Pratham Kakkar
Roll no:09115603120
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(sql1);

while (result.next())
{
System.out.println (result.getInt(1)+" "+
result.getString(2)+" "+
result.getString(3)+" "+
result.getString(4));
}

//Update the record


String sql2 = "Update Emp set email = ? where empname = ?";
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, "[email protected]");
pstmt.setString(2, "Jaya");
int rowUpdate = pstmt.executeUpdate();
if (rowUpdate > 0)
{
System.out.println("\nRecord updated successfully!!\n");
}

//Delete the record


String sql3 = "DELETE FROM Emp WHERE empname=?";
PreparedStatement statement1 = con.prepareStatement(sql3);
statement1.setString(1, "Prashant");

int rowsDeleted = statement1.executeUpdate();


if (rowsDeleted > 0)
{
System.out.println("A Employee was deleted successfully!\n");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

Pratham Kakkar
Roll no:09115603120
Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 21

Aim: Develop a scientific calculator using swings.

Theory: A Scientific Calculator is a very powerful and general purpose


calculator. In addition to basic arithmetic functions, it provides trigonometric
functions, logarithms, powers, roots etc. Therefore, these calculators are widely
used in any situation where quick access to certain mathematical functions is
needed. Here we are going to create a Scientific calculator using java swing.

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

public class ScientificCalculator extends JFrame implements ActionListener {


JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;

ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();

Pratham Kakkar
Roll no:09115603120
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc = new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);

mp = new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);

mm = new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);

b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);

b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
Pratham Kakkar
Roll no:09115603120
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);

b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);

zero = new JButton("0");


buttonpanel.add(zero);
zero.addActionListener(this);

plus = new JButton("+");


buttonpanel.add(plus);
plus.addActionListener(this);

min = new JButton("-");


buttonpanel.add(min);
min.addActionListener(this);

mul = new JButton("*");


buttonpanel.add(mul);
mul.addActionListener(this);

div = new JButton("/");


div.addActionListener(this);
buttonpanel.add(div);

addSub = new JButton("+/-");


buttonpanel.add(addSub);
addSub.addActionListener(this);

dot = new JButton(".");


Pratham Kakkar
Roll no:09115603120
buttonpanel.add(dot);
dot.addActionListener(this);

eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);

rec = new JButton("1/x");


buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);

sin = new JButton("SIN");


buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);

clr = new JButton("AC");


Pratham Kakkar
Roll no:09115603120
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String s = e.getActionCommand();
if (s.equals("1")) {
if (z == 0) {
tfield.setText(tfield.getText() + "1");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2")) {
if (z == 0) {
tfield.setText(tfield.getText() + "2");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3")) {
if (z == 0) {
tfield.setText(tfield.getText() + "3");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4")) {
if (z == 0) {
tfield.setText(tfield.getText() + "4");
} else {
Pratham Kakkar
Roll no:09115603120
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5")) {
if (z == 0) {
tfield.setText(tfield.getText() + "5");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6")) {
if (z == 0) {
tfield.setText(tfield.getText() + "6");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
Pratham Kakkar
Roll no:09115603120
}
if (s.equals("9")) {
if (z == 0) {
tfield.setText(tfield.getText() + "9");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0")) {
if (z == 0) {
tfield.setText(tfield.getText() + "0");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
Pratham Kakkar
Roll no:09115603120
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals(".")) {
if (y == 0) {
Pratham Kakkar
Roll no:09115603120
tfield.setText(tfield.getText() + ".");
y = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals("+")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '+';
} else {
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '-';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '/';
} else {
Pratham Kakkar
Roll no:09115603120
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '*';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC")) {
m1 = 0;
tfield.setText("");
}
if (s.equals("MR")) {
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-")) {
Pratham Kakkar
Roll no:09115603120
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.tan(Double.parseDouble(tfield.getText()));
Pratham Kakkar
Roll no:09115603120
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("=")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
temp1 = Double.parseDouble(tfield.getText());
switch (ch) {
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}

Pratham Kakkar
Roll no:09115603120
double fact(double x) {
int er = 0;
if (x < 0) {
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}

public static void main(String args[]) {


try {
UIManager

.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFee
l");
} catch (Exception e) {
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}

Output:

Pratham Kakkar
Roll no:09115603120
Experiment No. 22

Aim: Create an editor like MS-word using swings.

Theory:

Program:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class TextAreaInDocument extends JFrame{


JTextArea area;
JScrollPane pane;
JButton b1;
File file = new File("C:/New.doc");

private static void writeDoc(String FileName,String content){


try{
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry directory = fs.getRoot();
directory.createDocument("WordDocument", new
ByteArrayInputStream(content.getBytes()));
FileOutputStream out = new FileOutputStream(FileName);

fs.writeFilesystem(out);
out.close();
}
catch(Exception ex){
System.out.println(ex.getMessage());
}

Pratham Kakkar
Roll no:09115603120
}

TextAreaInDocument(){
area=new JTextArea(10,50);
area.setFont(new Font("courier New",Font.BOLD,12));
pane=new JScrollPane(area);
b1=new JButton("Create");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text=area.getText();
String f=file.getPath();
writeDoc(f,text);
area.setText("");
}
});

JPanel p=new JPanel();


p.add(pane);
p.add(b1);
add(p);
setVisible(true);
pack();
}
public static void main(String[]args){
TextAreaInDocument doc=new TextAreaInDocument();
}
}

Output:

Pratham Kakkar
Roll no:09115603120

You might also like