You are on page 1of 43

JAVA PRACTICAL FILE

Name
Branch
Roll no
Program 1: Create the program to take input for two numbers and add them.
Code:
import java.util.*;

public class Addition {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num1, num2, sum;
        System.out.print("Enter the first number:");
        num1 = sc.nextInt();
        System.out.print("Enter the second number:");
        num2 = sc.nextInt();
        sum = num1 + num2;
        System.out.println("Sum of these numbers: " + sum);
        sc.close();
    }
}

Output:
Enter the first number: 23
Enter the second number: 45
Sum of these numbers: 68

Program 2: Write a program to write command line arguments procedure, constructor


overloading.
Code:
class Box {
    double width, height, depth;

    Box(double w, double h, double d) {


        width = w;
        height = h;
        depth = d;
    }

    Box() {
        width = height = depth = 0;
    }

    Box(double len) {
        width = height = depth = len;
    }

    double volume() {
        return width * height * depth;
    }
}

// Driver code
public class Test {
    public static void main(String args[]) {
        Box mybox1 = new Box(10, 20, 15);
        Box mybox2 = new Box();
        Box mycube = new Box(7);
        double vol;
        vol = mybox1.volume();
        System.out.println(" Volume of mybox1 is " + vol);
        vol = mybox2.volume();
        System.out.println(" Volume of mybox2 is " + vol);
        vol = mycube.volume();
        System.out.println(" Volume of mycube is " + vol);
    }
}

Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

Program 3: Create a customized exception and also make use of all the 5 exception
keywords.
Code:
class MyException extends Exception {
    public MyException(String s) {
        // Call constructor of parent Exception
        super(s);
    }
}

// A Class that uses above MyException


public class Test {
    // Driver Program
    public static void main(String args[]) {
        try {
            // Throw an object of user defined exception
            throw new MyException("It’s an exception");
        } catch (MyException ex) {
            System.out.println("Caught");

            // Print the message from MyException object


            System.out.println(ex.getMessage());
        }
    }
}

Output:
Caught
It’s an exception

Program 4: Write a program for Star pattern, switch case example, exception handling
for an age exception.
Code:
import java.util.Scanner;

public class Pattern1 {


    public static void main(String[] args) {
        // Create a new Scanner object
        Scanner scanner = new Scanner(System.in);

        // Get the number of rows from the user


        System.out.println("Enter the number of rows needed to print the
pattern ");

        int rows = scanner.nextInt();


        System.out.println("## Printing the pattern ##");

        // Print i number of stars


        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        scanner.close();
    }
}

Output:
Enter the number of rows needed to print the pattern
3
## Printing the pattern ##
*
**
***

Switch Case Example:


public class Switch {
    public static void main(String[] args) {
        // Declaring a variable for switch expression
        int number = 20;
        // Switch expression
        switch (number) {
            // Case statements
            case 10:
                System.out.println("10");
                break;
            case 20:
                System.out.println("20");
                break;
            case 30:
                System.out.println("30");
                break;
            // Default case statement
            default:
                System.out.println("Not in 10, 20 or 30");
        }
    }
}

Output:
20

Exception Handling:
import java.util.Scanner;
     
class AgeException extends Exception {
 
 public AgeException(String str) {
  System.out.println(str);
 }
}
public class AgeExcDemo {
 
 public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  System.out.print("Enter ur age :: ");
  int age = s.nextInt();
 
  try {
   if(age < 18)
    throw new AgeException("Invalid age");
   else
    System.out.println("Valid age");
  }
  catch (AgeException a) {
   System.out.println(a);
  }
 }
}

Output:
Enter ur age :: 15
Invalid age
exception.AgeException
Enter ur age :: 20
Valid age

Program 5: Demonstrate the Abstract class example, static class example, stack push
pop operation.
Code:
abstract class Bike {
    abstract void run();
}

class Honda4 extends Bike {


    void run() {
        System.out.println("running safely");
    }

    public static void main(String args[]) {


        Bike obj = new Honda4();
        obj.run();
    }
}
Output: running safely
class OuterClass {
    private static String msg = "Apple";
 
    // Static nested class
    public static class NestedStaticClass {
 
        // Only static members of Outer class
        // is directly accessible in nested
        // static class
        public void printMessage()
        {
 
            // Try making 'message' a non-static
            // variable, there will be compiler error
            System.out.println(
                "Message from nested static class: "
                + msg);
        }
    }
 
    // Non-static nested class -
    // also called Inner class
    public class InnerClass {
 
        // Both static and non-static members
        // of Outer class are accessible in
        // this Inner class
        public void display()
        {
            System.out.println(
                "Message from non-static nested class: "
                + msg);
        }
    }
}
class Main {
    // How to create instance of static
    // and non static nested class?
    public static void main(String args[])
    {
 
        // Create instance of nested Static class
        OuterClass.NestedStaticClass printer
            = new OuterClass.NestedStaticClass();
 
        // Call non static method of nested
        // static class
        printer.printMessage();
 
        // In order to create instance of
        // Inner class we need an Outer class
        // instance. Let us create Outer class
        // instance for creating
        // non-static nested class
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner
            = outer.new InnerClass();
 
        // Calling non-static method of Inner class
        inner.display();
 
        // We can also combine above steps in one
        // step to create instance of Inner class
        OuterClass.InnerClass innerObject
            = new OuterClass().new InnerClass();
 
        // Similarly we can now call Inner class method
        innerObject.display();
    }
}

Output: Message from nested static class: Apple


Message from non-static nested class: Apple
Message from non-static nested class: Apple

import java.util.*;
 
public class Stack {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<Integer> STACK = new Stack<Integer>();
 
        // Use add() method to add elements
        STACK.push(10);
        STACK.push(15);
        STACK.push(30);
        STACK.push(20);
        STACK.push(5);
 
        // Displaying the Stack
        System.out.println("Initial Stack: " + STACK);
 
        // Removing elements using pop() method
        System.out.println("Popped element: " +
                                         STACK.pop());
        System.out.println("Popped element: " +
                                         STACK.pop());
 
        // Displaying the Stack after pop operation
        System.out.println("Stack after pop operation "
                                             + STACK);
    }
}
Output: Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]

Program 6: Write a program for Anonymous Class implementation.


Code:
interface Age {

    // Defining variables and methods


    int x = 21;

    void getAge();
}

// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {

    // Overriding getAge() method


    @Override
    public void getAge() {
        // Print statement
        System.out.print("Age is " + x);
    }
}

// Class 2
// Main class
// AnonymousDemo
class AnonymousClassInterpretation {
    // Main driver method
    public static void main(String[] args) {
        // Class 1 is implementation class of Age interface
        MyClass obj = new MyClass();

        // calling getage() method implemented at Class1


        // inside main() method
        obj.getAge();
    }
}

Output:
Age is 21

Program 7: Develop an analog clock using Applet.


Code:
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();
        }
    }
 
    // 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);
        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:
Program 8: Write a java program to show dynamic polymorphism and interfaces.
Code:
public class DynamicPolymorphism  
{  
public static void main(String args[])  
{  
//assigning a child class object to a parent class reference  
Fruits fruits = new Mango();  
//invoking the method  
fruits.color();                
}  
}  
//parent class  
class Fruits  
{  
public void color()  
{  
System.out.println("Parent class method is invoked.");  
}  
}  
//derived or child class that extends the parent class  
class Mango extends Fruits  
{  
//overrides the color() method of the parent class  
@Override  
public void color()  
{  
System.out.println("The child class method is invoked.");  
}  
}  

Output:
The child class method is invoked.

Interface example:
interface printable{  
    void print();  
    }  
    class A6 implements printable{  
    public void print(){System.out.println("Hello");}  
     
    public static void main(String args[]){  
    A6 obj = new A6();  
    obj.print();  
     }  
    }  

Output: Hello
Program 9: Write a program in Java to implement Queue concept.
Code:
public class Queue {
    int SIZE = 5;
    int items[] = new int[SIZE];
    int front, rear;

    Queue() {
        front = -1;
        rear = -1;
    }

    // check if the queue is full


    boolean isFull() {
        if (front == 0 && rear == SIZE - 1) {
            return true;
        }
        return false;
    }

    // check if the queue is empty


    boolean isEmpty() {
        if (front == -1)
            return true;
        else
            return false;
    }

    // insert elements to the queue


    void enQueue(int element) {

        // if queue is full
        if (isFull()) {
            System.out.println("Queue is full");
        } else {
            if (front == -1) {
                // mark front denote first element of queue
                front = 0;
            }

            rear++;
            // insert element at the rear
            items[rear] = element;
            System.out.println("Insert " + element);
        }
    }

    // delete element from the queue


    int deQueue() {
        int element;

        // if queue is empty
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return (-1);
        } else {
            // remove element from the front of queue
            element = items[front];

            // if the queue has only one element


            if (front >= rear) {
                front = -1;
                rear = -1;
            } else {
                // mark next element as the front
                front++;
            }
            System.out.println(element + " Deleted");
            return (element);
        }
    }

    // display element of the queue


    void display() {
        int i;
        if (isEmpty()) {
            System.out.println("Empty Queue");
        } else {
            // display the front of the queue
            System.out.println("\nFront index-> " + front);

            // display element of the queue


            System.out.println("Items -> ");
            for (i = front; i <= rear; i++)
                System.out.print(items[i] + "  ");

            // display the rear of the queue


            System.out.println("\nRear index-> " + rear);
        }
    }
    public static void main(String[] args) {

        // create an object of Queue class


        Queue q = new Queue();

        // try to delete element from the queue


        // currently queue is empty
        // so deletion is not possible
        q.deQueue();

        // insert elements to the queue


        for (int i = 1; i < 6; i++) {
            q.enQueue(i);
        }

        // 6th element can't be added to queue because queue is full


        q.enQueue(6);

        q.display();

        // deQueue removes element entered first i.e. 1


        q.deQueue();

        // Now we have just 4 elements


        q.display();

    }
}

Output:
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
1 2 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4

Program 10: Create a Java program for string reversal.


Code:
import java.util.*;

public class StringTransformation {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        System.out.println("Upper Case String: " + str.toUpperCase());
        String reversedString = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            char ch = str.charAt(i);
            reversedString = reversedString + ch;
        }
        System.out.println("Reversed String: " + reversedString);
        Vector<Character> vowels = new Vector<Character>();
        Vector<Character> consonants = new Vector<Character>();
        str = str.toLowerCase();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if ((ch == 'a') || (ch == 'e') || (ch == 'i') || (ch == 'o') ||
(ch == 'u'))
                vowels.add(ch);
            else if ((ch >= 'a') && (ch <= 'z'))
                consonants.add(ch);
        }
        System.out.print("Vowels: ");
        for (int i = 0; i < vowels.size(); i++) {
            char ch = vowels.get(i);
            System.out.print(ch);
        }
        System.out.println();
        System.out.print("Consonants: ");
        for (int i = 0; i < consonants.size(); i++) {
            char ch = consonants.get(i);
            System.out.print(ch);
        }
        sc.close();
    }
}

Output:
Enter a string: Applet
Upper Case String: APPLET
Reversed String: telppA
Vowels: ae
Consonants: pplt

Program 11: Write a program to convert infix to postfix notation.


Code:
import java.util.Stack;

class Test {

    // A utility function to return


    // precedence of a given operator
    // Higher returned value means
    // higher precedence
    static int Prec(char ch) {
        switch (ch) {
            case '+':
            case '-':
                return 1;

            case '*':
            case '/':
                return 2;

            case '^':
                return 3;
        }
        return -1;
    }

    // The main method that converts


    // given infix expression
    // to postfix expression.
    static String infixToPostfix(String exp) {
        // initializing empty String for result
        String result = new String("");

        // initializing empty stack


        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < exp.length(); ++i) {


            char c = exp.charAt(i);

            // If the scanned character is an


            // operand, add it to output.
            if (Character.isLetterOrDigit(c))
                result += c;

            // If the scanned character is an '(',


            // push it to the stack.
            else if (c == '(')
                stack.push(c);

            // If the scanned character is an ')',


            // pop and output from the stack
            // until an '(' is encountered.
            else if (c == ')') {
                while (!stack.isEmpty() &&
                        stack.peek() != '(')
                    result += stack.pop();

                stack.pop();
            } else // an operator is encountered
            {
                while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())) {

                    result += stack.pop();
                }
                stack.push(c);
            }

        }

        // pop all the operators from the stack


        while (!stack.isEmpty()) {
            if (stack.peek() == '(')
                return "Invalid Expression";
            result += stack.pop();
        }
        return result;
    }

    // Driver method
    public static void main(String[] args) {
        String exp = "a+b*(c^d-e)^(f+g*h)-i";
        System.out.println(infixToPostfix(exp));
    }
}

Output:
abcd^e-fgh*+^*+i-

Program 12: Write a java program to show multithreaded producer and consumer
application.
Code:
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 ifrst 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:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2

Program 13: Develop a scientific calculator using swings.


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();
                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);
        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(".");


        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");


        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 {
                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;
            }
        }
        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("");
                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) {
                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 {
                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-")) {
            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()));
                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();
    }

    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.WindowsLookAndFeel");
        } catch (Exception e) {
        }
        ScientificCalculator f = new ScientificCalculator();
        f.setTitle("ScientificCalculator");
        f.pack();
        f.setVisible(true);
    }
}

Output:

Program 14: Create an editor like MS-Word using swings.


Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
import javax.swing.text.*;
class editor extends JFrame implements ActionListener {
    // Text component
    JTextArea t;
 
    // Frame
    JFrame f;
 
    // Constructor
    editor()
    {
        // Create a frame
        f = new JFrame("editor");
 
        try {
            // Set metal look and feel
           
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
 
            // Set theme to ocean
            MetalLookAndFeel.setCurrentTheme(new OceanTheme());
        }
        catch (Exception e) {
        }
 
        // Text component
        t = new JTextArea();
 
        // Create a menubar
        JMenuBar mb = new JMenuBar();
 
        // Create amenu for menu
        JMenu m1 = new JMenu("File");
 
        // Create menu items
        JMenuItem mi1 = new JMenuItem("New");
        JMenuItem mi2 = new JMenuItem("Open");
        JMenuItem mi3 = new JMenuItem("Save");
        JMenuItem mi9 = new JMenuItem("Print");
 
        // Add action listener
        mi1.addActionListener(this);
        mi2.addActionListener(this);
        mi3.addActionListener(this);
        mi9.addActionListener(this);
 
        m1.add(mi1);
        m1.add(mi2);
        m1.add(mi3);
        m1.add(mi9);
 
        // Create amenu for menu
        JMenu m2 = new JMenu("Edit");
 
        // Create menu items
        JMenuItem mi4 = new JMenuItem("cut");
        JMenuItem mi5 = new JMenuItem("copy");
        JMenuItem mi6 = new JMenuItem("paste");
 
        // Add action listener
        mi4.addActionListener(this);
        mi5.addActionListener(this);
        mi6.addActionListener(this);
 
        m2.add(mi4);
        m2.add(mi5);
        m2.add(mi6);
 
        JMenuItem mc = new JMenuItem("close");
 
        mc.addActionListener(this);
 
        mb.add(m1);
        mb.add(m2);
        mb.add(mc);
 
        f.setJMenuBar(mb);
        f.add(t);
        f.setSize(500, 500);
        f.show();
    }
 
    // If a button is pressed
    public void actionPerformed(ActionEvent e)
    {
        String s = e.getActionCommand();
 
        if (s.equals("cut")) {
            t.cut();
        }
        else if (s.equals("copy")) {
            t.copy();
        }
        else if (s.equals("paste")) {
            t.paste();
        }
        else if (s.equals("Save")) {
            // Create an object of JFileChooser class
            JFileChooser j = new JFileChooser("f:");
 
            // Invoke the showsSaveDialog function to show the save dialog
            int r = j.showSaveDialog(null);
 
            if (r == JFileChooser.APPROVE_OPTION) {
 
                // Set the label to the path of the selected directory
                File fi = new File(j.getSelectedFile().getAbsolutePath());
 
                try {
                    // Create a file writer
                    FileWriter wr = new FileWriter(fi, false);
 
                    // Create buffered writer to write
                    BufferedWriter w = new BufferedWriter(wr);
 
                    // Write
                    w.write(t.getText());
 
                    w.flush();
                    w.close();
                }
                catch (Exception evt) {
                    JOptionPane.showMessageDialog(f, evt.getMessage());
                }
            }
            // If the user cancelled the operation
            else
                JOptionPane.showMessageDialog(f, "the user cancelled the
operation");
        }
        else if (s.equals("Print")) {
            try {
                // print the file
                t.print();
            }
            catch (Exception evt) {
                JOptionPane.showMessageDialog(f, evt.getMessage());
            }
        }
        else if (s.equals("Open")) {
            // Create an object of JFileChooser class
            JFileChooser j = new JFileChooser("f:");
 
            // Invoke the showsOpenDialog function to show the save dialog
            int r = j.showOpenDialog(null);
 
            // If the user selects a file
            if (r == JFileChooser.APPROVE_OPTION) {
                // Set the label to the path of the selected directory
                File fi = new File(j.getSelectedFile().getAbsolutePath());
 
                try {
                    // String
                    String s1 = "", sl = "";
 
                    // File reader
                    FileReader fr = new FileReader(fi);
 
                    // Buffered reader
                    BufferedReader br = new BufferedReader(fr);
 
                    // Initialize sl
                    sl = br.readLine();
 
                    // Take the input from the file
                    while ((s1 = br.readLine()) != null) {
                        sl = sl + "\n" + s1;
                    }
 
                    // Set the text
                    t.setText(sl);
                }
                catch (Exception evt) {
                    JOptionPane.showMessageDialog(f, evt.getMessage());
                }
            }
            // If the user cancelled the operation
            else
                JOptionPane.showMessageDialog(f, "the user cancelled the
operation");
        }
        else if (s.equals("New")) {
            t.setText("");
        }
        else if (s.equals("close")) {
            f.setVisible(false);
        }
    }
 
    // Main class
    public static void main(String args[])
    {
        editor e = new editor();
    }
}

Output:
 

 
 

Program 15: Create a GUI for storing the students information and write it to file &
save to database as well.
Code:
import java.awt.*;
import java.awt.event.*;

class Student extends Frame implements ActionListener {


    Label lsname, lsrollno, lsclass, lgender, lsbg, lsmob, lsadrs;
    CheckboxGroup gender;
    Checkbox male, female, trainpass;
    Choice csclass;
    TextField tfsname, tfsrollno, tfsmob;
    TextArea tasadrs;
    Button submit;

    TextArea display_details;

    Student() {
        setBackground(Color.CYAN);
        lsname = new Label("Name : ");
        lsrollno = new Label("Roll No : ");
        lsclass = new Label("Class : ");
        lgender = new Label("Gender : ");

        lsmob = new Label("Mobile : ");


        lsadrs = new Label("Address : ");

        gender = new CheckboxGroup();


        male = new Checkbox("Male", gender, false);
        female = new Checkbox("Female", gender, false);

        csclass = new Choice();


        csclass.add("B.Tech Computer Science");
        csclass.add("B.Tech ECE");
        csclass.add("B.Tech Civil");
        csclass.add("B.Tech IT");
        csclass.add("B.Tech Mechanical");
        csclass.add("None of These");

        tfsname = new TextField();


        tfsrollno = new TextField();
        tfsmob = new TextField();

        tasadrs = new TextArea("", 2, 100, TextArea.SCROLLBARS_NONE);

        submit = new Button("Submit");

        display_details = new TextArea("", 2, 100, TextArea.SCROLLBARS_NONE);


        display_details.setEditable(false);

        lsname.setBounds(10, 30, 50, 20);


        tfsname.setBounds(70, 30, 150, 20);

        lsrollno.setBounds(240, 30, 50, 20);


        tfsrollno.setBounds(300, 30, 150, 20);

        lsclass.setBounds(10, 60, 50, 20);


        csclass.setBounds(70, 60, 150, 20);

        lgender.setBounds(240, 60, 50, 20);


        male.setBounds(300, 60, 50, 20);
        female.setBounds(360, 60, 50, 20);

        lsmob.setBounds(10, 90, 50, 20);


        tfsmob.setBounds(70, 90, 150, 20);

        lsadrs.setBounds(10, 120, 50, 20);


        tasadrs.setBounds(70, 120, 380, 70);

        submit.setBounds(10, 200, 440, 30);

        display_details.setBounds(10, 240, 440, 130);

        add(lsname);
        add(lsrollno);
        add(lsclass);
        add(lgender);
        add(lsadrs);
        add(lsmob);

        add(male);
        add(female);

        add(csclass);

        add(tfsname);
        add(tfsrollno);
        add(tasadrs);
        add(tfsmob);

        add(submit);

        add(display_details);

        submit.addActionListener(this);

        setTitle("Students Details");
        setSize(460, 390);
        setLayout(null);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });
    }

    public void actionPerformed(ActionEvent e) {


        if (e.getSource() == submit) {

            String sdetails = " ***** Students Details *****n Name : " +


tfsname.getText() + "n Roll No. :"
                    + tfsrollno.getText() + "n Class : " +
csclass.getSelectedItem() + "n Gender : "
                    + gender.getSelectedCheckbox().getLabel() + "n Mobile : "
+ tfsmob.getText() + "n Address : "
                    + tasadrs.getText();

            display_details.setText(sdetails);
        }
    }

    public static void main(String[] args) {


        new Student();
    }
}

Output:

Program 16: Convert the content of a given file into uppercase content.
Code:
import java.io.*;  

public class fileDemo {


   
    static void toUpper() throws Exception{
       
            FileReader fr=new FileReader("/uploads/java_lab.txt");    
            BufferedReader br=new BufferedReader(fr);    
            FileWriter writer = new FileWriter("/myfiles/output.txt");  
            BufferedWriter buffer = new BufferedWriter(writer);  
            int i;    
            char ch, ch1;
            while((i=br.read())!=-1){
                ch = (char)i;
                ch1 = Character.toUpperCase(ch);  
                buffer.write(ch1);  
            }  
            br.close();    
            fr.close();  
            buffer.close();  
            writer.close();
    }
   
    static void voweltoUpper() throws Exception{
       
            FileReader fr=new FileReader("/uploads/java_lab.txt");    
            BufferedReader br=new BufferedReader(fr);    
            FileWriter writer = new FileWriter("/myfiles/output.txt");  
            BufferedWriter buffer = new BufferedWriter(writer);  
            int i;    
            char ch, ch1;
            while((i=br.read())!=-1){
                ch = (char)i;
                ch1 = Character.toUpperCase(ch);  
                if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
                   buffer.write(ch1);
                }else{
                    buffer.write(ch);
                }
            }
            br.close();    
            fr.close();  
            buffer.close();  
            writer.close();
    }
   
    public static void main(String args[]) throws Exception {
        try{
            // toUpper();
            voweltoUpper();
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

Output:
ThIs Is my fIrst prOgrAm. It Is In JAvA.

You might also like