0% found this document useful (0 votes)
51 views48 pages

Ii Bca Java Program All

The document outlines various Java programs, including generating prime numbers, matrix multiplication, counting characters in a file, generating random numbers, and performing string manipulations using different classes. Each section includes an aim, algorithm, program code, and a result indicating successful execution. The programs demonstrate fundamental programming concepts such as loops, conditionals, and object-oriented programming.

Uploaded by

reenasambu
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)
51 views48 pages

Ii Bca Java Program All

The document outlines various Java programs, including generating prime numbers, matrix multiplication, counting characters in a file, generating random numbers, and performing string manipulations using different classes. Each section includes an aim, algorithm, program code, and a result indicating successful execution. The programs demonstrate fundamental programming concepts such as loops, conditionals, and object-oriented programming.

Uploaded by

reenasambu
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/ 48

EX.

NO: 01
PRIME NUMBERS
DATE:

AIM:
To write a java program to generate prime numbers between the given range of numbers

ALGORITHM:

Step 1: Start the program


Step 2: Declare the necessary variables
Step 3: Read the values to the variables a and b
Step 4: Check the condition using for loop and get the values
Step 5: Initialize the variable flag =0
Step 6: Using for loop, check if (i%j==0) if the condition is true set flag=0
Step 7: Check if(flag==1) if the condition is true print the value of variable i
Step 8: Stop the program

PROGRAM:

import java.io.*;
class prime
{
public static void main(String[] args) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
int a, b, i, j, flag;
System.out.println(" \n\t\t GENERATING PRIME NUMBERS ");
System.out.println(" \t\t ~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print("\n\n \t\t ENTER THE FIRST NUMBR : ");
a = Integer.parseInt(in.readLine());
System.out.print("\n\n\t\t ENTER THE SECOND NUMBER : ");
b = Integer.parseInt(in.readLine());
System.out.printf("\n\n\t\t THE PRIME NUMBERS BETWEEN %d AND %d ARE : ", a, b);
for (i = a; i <= b; i++)
{
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j)
{
if (i % j == 0)
{
flag = 0;
break;
}
}
if (flag == 1)
System.out.print( " "+i+" " );
}
}
}

OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 02
MATRIX MULTIPLICATION
DATE:

AIM:
To write a java program to multiply the given two matrices.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the class matrixmultiply.
Step 3: Declare the necessary variables.
Step 4: Read the values m,n,p & q to get the order of the matrix.
Step 5: Read the values of matrix first & second using for loop.
Step 6: Using nested for loop calculate sum=sum +first [i] [k]*second [k] [j].
Step 7: Using nested for loop print the values of matrix first, second & result matrix.
Step 8: Run the program.
Step 9: Stopthe program.

PROGRAM:
import java.io.*;
import java.util.Scanner;
class matrixmultiply
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, i, j, k;
Scanner in = new Scanner(System.in);
System.out.println("\n\n\t MULTIPLICATION OF TWO MATRICES \n\n\t
================================");
System.out.println("\nENTER THE ORDER OF THE MATRIX A:");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("\nENTER THE ORDER OF THE MATRIX B:");
p = in.nextInt();
q = in.nextInt();
if (n != p)
System.out.println("\n\t MATRIX MULTIPLICATION IS IMPOSSIBLE \n\t ROWS AND
COLUMNS DOES NOT MATCH");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("\n\t ENTER THE ELMENTS OF MATRIX A:\n\t
******************************");
for (i = 0; i < m; i++)
for (j= 0; j < n; j++)
first[i][j] = in.nextInt();
System.out.println("\n\t ENTER THE ELMENTS OF MATRIX B:\n\t
******************************");
for (i = 0; i< p; i++)
for (j= 0; j < q; j++)
second[i][j] = in.nextInt();

for (i = 0; i< m; i++)


{
for (j= 0; j < q; j++)
{
for (k = 0; k < p; k++)
{
sum = sum + first[i][k]*second[k][j];
}

multiply[i][j] = sum;
sum = 0;
}
}
System.out.println("\n\t MATRIX MULTIPLICATION \n\t ********************");
System.out.println("\n\t MATRIX A \n\t~~~~~~~~~");
for (i = 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print("\t"+first[i][j]);
System.out.print("\n");
}
System.out.println("\n\t MATRIX B \n\t~~~~~~~~~");
for (i= 0; i < m; i++)
{
for (j = 0; j < q; j++)
System.out.print("\t"+second[i][j]);

System.out.print("\n");
}
System.out.println("\n\t RESULT MATRIX \n\t --------------");

for (i = 0; i < m; i++)


{
for (j= 0; j < q; j++)
System.out.print("\t"+multiply[i][j]);

System.out.print("\n");
}
}
}
}

OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 03
COUNTING THE CHARACTERS WORDS AND LINES
DATE:

AIM:
To write a java program to count the number of characters words and lines in a text file.

ALGORITHM:
Step 1: Start the program.
Step 2: Define the class count
Step 3: Declare the necessary variables and initialize them to zero
Step 4: Using Buffered Reader stream read the text file “nithi.txt”.
Step 5: By using while loop count the total number of lines.
Step 6: Using for loop count the total number of words and characters.
Step 7: Print the result character words and line counts.
Step 8: Run the program.
Step 9: Stopthe program.

PROGRAM:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class count
{
public static void main(String[] args)
{
BufferedReader reader = null;
int cc = 0,wc = 0,lc= 0;
try
{
reader = new BufferedReader(new FileReader("nithi.txt"));
String currentLine = reader.readLine();
while (currentLine != null)
{
lc++;
String[] words = currentLine.split(" ");
wc= wc + words.length;
for (String word : words)
{
cc = cc + word.length();
}
currentLine = reader.readLine();
}
System.out.println("\n\n\t\t COUNTING THE CHARACTERS WORDS AND LINES IN A FILE ");
System.out.println("\t\t ================================================= ");
System.out.println("\n\t NUMBER OF CHARACTERS IN THE FILE NITHI.TXT : " +cc);
System.out.println("\n\t NUMBER OF WORDS IN THE FILE NITHI.TXT : "+wc);
System.out.println("\n\t NUMBER OF LINES IN THE FILE NITHI.TXT : "+lc);
}
catch (IOException e)
{
e.printStackTrace()
}
Finally
{
Try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 04
GENERATING RANDOM NUMBERS
DATE:

AIM:
To write a java program to generate Random numbers between the given limit.

ALGORITHM:

Step 1: Start the program.


Step 2: Define the class rannum
Step 3: Declare the necessary variables min, max.
Step 4: Get the values for min and max variables.
Step 5: By using the formula ‘random.nextInt(max-min+1)+min’generate the Random numbers.
Step 6: Print the result values.
Step 7: Run the program.
Step 8: Stop the program.

PROGRAM:
import java.util.Random;
import java.io.*;
class rannum
{
public static void main(String[] args) throws IOException
{
int min,max;
DataInputStream in=new DataInputStream(System.in);
Random random=new Random();
System.out.println(" \n\t\t\t GENERATING RANDOM NUMBERS ");
System.out.println("\t\t\t ========================== ");
System.out.print("\n\t\t ENTER THE LOWER LIMIT : ");
min=Integer.parseInt(in.readLine());
System.out.print("\n\t\t ENTER THE UPPER LIMIT : ");
max=Integer.parseInt(in.readLine());
System.out.println("\n\t\t THE RANDOM NUMBERS BETWEEN : " +min+ " TO " +max);
System.out.print("\n\t\t");
System.out.print( random.nextInt(max-min+1)+min+"\t");
System.out.print( random.nextInt(max-min+1)+min+"\t");
System.out.print( random.nextInt(max-min+1)+min+"\t");
System.out.print( random.nextInt(max-min+1)+min+"\t");
System.out.print("\n\n\t");
}
}
OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 05
STRING MANIPULATIONS USING CHARACTER
ARRAYS
DATE:

AIM:
To write a java program to perform string manipulations using character arrays.

ALGORITHM:

Step 1: Start the program.


Step 2: Define the class strfun
Step 3: Declare the necessary string and integer variables.
Step 4: Get the input to the string variables str1 and str2.
Step 5: Read the integer value to print the particular character in the variable str1.
Step 6: Print the length of the stings using str.length().
Step 7: Using if statement check the condition if (pos > 0 && pos <= str1.length()) to print the character
in the particular position otherwise, it will print invalid index.
Step 8: Concatenate the two strings str1 and str2 using the method str.concat() function
Step 9: Run the program.
Step 10: Stop the program.

PROGRAM:
import java.io.*;
class strfun
{
public static void main(String[] args) throws IOException
{
String str1,str2,str3 ;
DataInputStream st=new DataInputStream(System.in);
System.out.println("\n\n\t\t\t STRING HANDLING FUNCTIONS ");
System.out.println("\t\t\t ========================= ");
System.out.print("\n\t\t ENTER THE FIRST STRING : ");
str1=st.readLine();
System.out.print("\n\t\t ENTER THE SECOND STRING : ");
str2=st.readLine();
System.out.print("\n\t\t ENTER THE POSITION TO READ : ");
int pos = Integer.parseInt(st.readLine());
System.out.println("\n\t\t THE LENGTH OF THE FIRST STRING : "+str1+" IS =
"+str1.length());
System.out.println("\n\t\t THE LENGTH OF THE SECOND STRING : "+str2+" IS =
"+str2.length());
if (pos > 0 && pos <= str1.length())
{
char ch = str1.charAt(pos - 1);
System.out.println("\n\t\t CHARACTER AT POSITION : " + pos + " IS = " + ch);
}
else
{
System.out.println("\n\t\t INVALID INDEX ");
}
str3=str1.concat(str2);
System.out.println("\n\t\t CONCATENATION OF TWO STRINGS :"+ str1 +" AND " + str2 + " IS
= "+str3);
}
}

OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 06
STRING MANIPULATIONS USING STRING CLASS
DATE:

AIM:
To write a program to perform string manipulation using string class
ALGORITHM:
Step 1: Start the program.
Step 2: Read the values using data.
Step 3: Read the values for three string.
Step 4: concatenate string using concat() function.
Step 5: Check whether String present in given String using Contains () method.
Step 6: Slice the part of the given string using Substring () method
Step 7: Stop the program

PROGRAM:
import java.io.*;
class fun
{
public static void main(String[] args) throws IOException
{
String txt,str1,str2,str3;
int position;
DataInputStream st=new DataInputStream(System.in);
System.out.println("\n\n\t\t\t STRING HANDLING FUNCTIONS ");
System.out.println("\t\t\t ========================= ");
System.out.print("\n\t\t ENTER THE TEXT TO FIND THE SUBSTRING : ");
txt=st.readLine();
System.out.print("\n\t\t ENTER THE FIRST STRING : ");
str1=st.readLine();
System.out.print("\n\t\t ENTER THE SECOND STRING : ");
str2=st.readLine();
str3=str1.concat(str2);
System.out.print("\n\t\t ENTER THE POSITION TO FIND THE SUB STRING : ");
position=Integer.parseInt(st.readLine());
System.out.print("\n\n\t\t ================================================== ");
System.out.println("\n\t\t CONCATENATION OF TWO STRINGS :"+ str1 +" AND " + str2 + " IS
= "+str3);
boolean result = txt.contains(str1);
if(result)
{
System.out.println("\n\t\t THE GIVEN SUB STRING : " + str1 + " IS PRESENT IN THE STRING.
");
}
else
{
System.out.println("\n\t\t THE GIVEN SUB STRING : " + str2 + " IS NOT PRESENT IN THE
STRING. ");
}
result = txt.contains(str2);
if(result)
{
System.out.println("\n\t\t THE GIVEN SUB STRING : " + str1 + " IS PRESENT IN THE STRING.
");
}
else
{
System.out.println("\n\t\t THE GIVEN SUB STRING : " + str2 + " IS NOT PRESENT IN THE
STRING. ");
}
System.out.println("\n\t\t THE SUB STRING AT THE PARTICULAR POSITION : " + position +" :
" + txt.substring(position));
System.out.print("\n\n\t\t =================================================== ");
}
}
OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 07
STRING MANIPULATIONS USING STRING BUFFER
CLASS
DATE:

AIM:
To write a program to perform string manipulation using string Buffer class

ALGORITHM:
Step 1: Start the program.
Step 2: Declare necessary variable.
Step 3: Create an object for String Buffer.
Step 4: Find the length of the String using length () method.
Step 5: Remove the part of the String using delete ().
Step 6: Reverse the given String reverse () method.
Step 7: Stop the program

PROGRAM:
import java.io.*;
import java.lang.*;
class sbuffer
{
public static void main(String[] args) throws IOException
{
int length,start,end;
StringBuffer sb = new StringBuffer(" SREE HANISH PRABHAKARAN");
System.out.println("\n\t\t\t STRING HANDLING FUNCTIONS USING STRING BUFFER
CLASS ");
System.out.println("\n\t\t\t
=================================================== ");
System.out.println(" \n\t\t THE GIVEN STRING BUFFER = " + sb);
length=sb.length() ;
sb.delete(13, 24);
System.out.println("\n\t\t LENGTH OF THE STRING IS = " + length);
System.out.println(" \n\t\t THE CONTENT OF THE STRING AFTER DELETION = " + sb);
sb.reverse();
System.out.println("\n\t\t THE CONTENT OF THE STRING REVERSE : " + sb);
}
}
OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 08
MULTI THREADING
DATE:

AIM:
To write a java program to perform multithreading

ALGORITHM:
Step 1: Start the program.
Step 2: Define the square which extends Thread.
Step 3: Define the constructor method Square () initialize the variable n.
Step 4: define run () method to calculate the square value.
Step 5: define the class cube () which extends thread.
Step 6: In cube () method initialize the variable n.
Step 7: Define the run () method calculate the cube value of given number.
Step 8: Define the class number which extends thread.
Step 9: Using the for loop, Print the integer value using nextInt ()
Step 10: Check the integer value divide by 2 which equal to zero.
Step 11: If Condition is true, create the object for the Class Square and call the Start() method.
Step 12: Otherwise, Create the object for the class and call the Start () function.
Step 13: In Main (), create an object for class Number.
Step 14: call the Start () function.
Step 15: Stop the program.

PROGRAM:

import java.io.*;
import java.util.Random;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println(" \t\t\t SQUARE VALUE OF X IS : " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("\t\t\t CUBE VALUE OF X IS : " + x + " = " + cub );
}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<15; i++)
{
int randomInteger = random.nextInt(100);
System.out.println(" \n\t\t\t RANDOM INTEGER IS GENERATED : " + randomInteger);
if(randomInteger%2==0)
{
Square s = new Square(randomInteger);
s.start();
}
else
{
Cube c = new Cube(randomInteger);
c.start();
}
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}
public class thread
{
public static void main(String args[])
{
System.out.println(" \t\t\t\t MULTI THREADING ");
System.out.println(" \t\t\t\t ~~~~~~~~~~~~~~~ ");
Number n = new Number();
n.start();
}
}

OUTPUT:
D:\PRABHA>javac thread.java
D:\PRABHA>java thread

MULTI THREADING
~~~~~~~~~~~~~~~~~

RANDOM INTEGER IS GENERATED : 89


CUBE VALUE OF X IS : 89 = 704969

RANDOM INTEGER IS GENERATED : 84


SQUARE VALUE OF X IS : 84 = 7056

RANDOM INTEGER IS GENERATED : 90


SQUARE VALUE OF X IS : 90 = 8100

RANDOM INTEGER IS GENERATED : 2


SQUARE VALUE OF X IS : 2 = 4

RANDOM INTEGER IS GENERATED : 6


SQUARE VALUE OF X IS : 6 = 36

RANDOM INTEGER IS GENERATED : 20


SQUARE VALUE OF X IS : 20 = 400

RANDOM INTEGER IS GENERATED : 12


SQUARE VALUE OF X IS : 12 = 144

RANDOM INTEGER IS GENERATED : 88


SQUARE VALUE OF X IS : 88 = 7744

RANDOM INTEGER IS GENERATED : 87


CUBE VALUE OF X IS : 87 = 658503

RANDOM INTEGER IS GENERATED : 37


CUBE VALUE OF X IS : 37 = 50653
RANDOM INTEGER IS GENERATED : 56
SQUARE VALUE OF X IS : 56 = 3136

RANDOM INTEGER IS GENERATED : 43


CUBE VALUE OF X IS : 43 = 79507

RANDOM INTEGER IS GENERATED : 35


CUBE VALUE OF X IS : 35 = 42875

RANDOM INTEGER IS GENERATED : 34


SQUARE VALUE OF X IS : 34 = 1156

RANDOM INTEGER IS GENERATED : 84


SQUARE VALUE OF X IS : 84 = 7056

D:\PRABHA>

RESULT:

Thus, the above program has been executed and verified successfully
EX.NO: 09
ASYNCHRONOUS THREADS
DATE:

AIM:
To write a java program to perform same method asynchronously threads to print the number

1 to 10 using thread1 and 90 to 100 using thread2

ALGORITHM:
Step 1: Start the program.
Step 2: Define the class printer which implement Runnable.
Step 3: Define Constructor, to assign start value, end value and thread name.
Step 4: In run () method, using for loop, print the value.
Step 5: Using try – catch block, Interrupt () the current thread.
Step 6: In main function, Create the object for class Printer.
Step 7: Start the thread using Start () method.
Step 8: Using try catch method join () the thread execution.
Step 9: Stop the program.
PROGRAM:
import java.io.*;
class Printer implements Runnable
{
private int start;
private int end;
private String threadName;
public Printer(int start, int end, String threadName)
{
this.start = start;
this.end = end;
this.threadName = threadName;
}
public void run()
{
for (int num = start; num <= end; num++)
{
System.out.println("\n\t\t\t"+threadName + ": " + num);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
}
class threadnum
{
public static void main(String[] args)
{
System.out.println("\n\t\t\t ASYNCHRONEOUS THREADS ");
System.out.println("\t\t\t ===================== ");
Thread thread1 = new Thread(new Printer(1, 10, "THREAD 1"));
Thread thread2 = new Thread(new Printer(90, 100, "THREAD 2"));
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
System.out.println("\n\t\t\t BOTH THE THREADS ARE FINISHED......");
}
}

OUTPUT:
D:\PRABHA>javac threadnum.java

D:\PRABHA>java threadnum

ASYNCHRONEOUS THREADS
========================

THREAD 1: 1
THREAD 2: 90
THREAD 2: 91
THREAD 1: 2
THREAD 2: 92
THREAD 1: 3
THREAD 2: 93
THREAD 1: 4
THREAD 2: 94
THREAD 1: 5
THREAD 2: 95
THREAD 1: 6
THREAD 1: 7
THREAD 2: 96
THREAD 2: 97
THREAD 1: 8
THREAD 1: 9
THREAD 2: 98
THREAD 2: 99
THREAD 1: 10
THREAD 2: 100

BOTH THE THREADS ARE FINISHED......

D:\PRABHA>

RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 10
EXCEPTION HANDLING
DATE:

AIM:

To write a java program to handle various types of exception

ALGORITHM:
Step 1: Start the program.
Step 2: Define the class, except, in main() function, using try-catch block, divide the number by 0.
Step 3: Assign the String and convert to Integer.
Step 4: Using try – catch block, Check the number format exception.
Step 5: Assign the value to the array of fixed size.
Step 6: Check the value of index is negative to print negative array size exception.
Step 7: Stop the program.

PROGRAM:
import java.io.*;
public class excep
{
public static void main(String[] args)
{
System.out.println("\n\t\t\t EXCEPTION HANDLING ");
System.out.println("\t\t\t =================== ");
try
{
int divideByZero = 10 / 0;
}
catch (ArithmeticException e)
{
System.out.println("\n\t\t ARITHMETIC EXCEPTION : " + e.getMessage());
}
try
{
String str = "abc";
int num = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
System.out.println(" \n\t\t NUMBER FORMAT EXCEPTION : "+ e.getMessage());
}
try
{
int[] array = new int[5];
System.out.println(array[10]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("\n\t\t ARRAY INDEX OUTOF BOUND EXCEPTION : " +
e.getMessage());
}
try
{
int[] array = new int[-5];
}
catch (NegativeArraySizeException e)
{
System.out.println("\n\t\t NEGATIVE ARRAY INDEX SIZE : " + e.getMessage());
}
}
}
OUTPUT:

RESULT:

Thus, the above program has been executed and verified successfully.
.
EX.NO: 11
FILE OPERATIONS
DATE:

AIM:

To write a java program to read a file and display the basic information about the file

ALGORITHM:
Step 1: Start the program.
Step 2: Define the main function in file class
Step 3: Create an object for file
Step 4: Check the file if it exist or not using exists() function
Step 5: Check the file if it able to read using canRead() file.
Step 6: Check the file, if it can able to write using canWrite() file.
Step 7: Check the file whether it is file or directory using isDirectory() function.
Step 8: Using try block, create an object for string buffer and also for file input stream.
Step 9: Using while loop read the character and append the character to the file
Step 10: Close the file using close() method
Step 11: In catch block, catch the error if the specified file not found and file cannot be read.
Step 12: Stop the program.

PROGRAM:

import java.io.*;
import javax.swing.*;
class file
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog(" ENTER THE FILE NAME : ");
File f = new File(filename);
System.out.println("\n\t\t\t FILE OPERATIONS ");
System.out.println("\t\t\t *************** ");
System.out.println("\t\t FILE EXISTS : "+f.exists());
System.out.println("\t\t FILE IS READABLE : "+f.canRead());
System.out.println("\t\t FILE IS WRITEABLE : "+f.canWrite());
System.out.println("\t\t FILE IS A DIRECTORY : "+f.isDirectory());
System.out.println(" \t THE LENGTH OF THE FILE IS : " +f.length()+ " bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\n\t THE CONTENT OF THE FILE : "+ filename );
System.out.println("\t =================================== ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("\n\t CANNOT FIND SPECIFIED FILE NAME : " +filename);
}
catch(IOException i)
{
System.out.println(" \n\t THE FILE : " + filename + "CANNOT BE READ ");
}
}
}

OUTPUT:
RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 12
TEXT EDITOR
DATE:

AIM:

To write a java program to accept a text and change its size and font. Include bold italic options

ALGORITHM:
Step 1: Start the program.
Step 2: Define the class texteditor which extends JFrame
Step 3: Create an object for Jcombobox nd Jchechbox
Step 4: Define the function Texteditor() which contains the control such as combobox and checkbox
Step 5: Add the control to the control panel and listener
Step 6: Add the border layout to the panel
Step 7: In action performed(), get the font size of the selected item Stop the program
Step 8: Define the class font changed to get the font name of the selected item.
Step 9: Define the class font style changed get the selected font style to change bold or italic
Step 10: In main function call the function texteditor()
Step 11: Stop the programs

PROGRAM:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class texteditor extends JFrame
{
private JTextPane textPane;
private JComboBox<String> fontSizeComboBox;
private JComboBox<String> fontComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public texteditor()
{
textPane = new JTextPane();
textPane.setFont(new Font("Arial", Font.PLAIN, 12));
fontSizeComboBox = new JComboBox<>(new String[] {"10", "12", "14", "16", "18", "20"});
fontSizeComboBox.addActionListener(new FontSizeChangeListener());
fontComboBox = new JComboBox<>(new String[] {"Arial", "Times New Roman", "Calibri",
"Courier New"});
fontComboBox.addActionListener(new FontChangeListener());
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(new FontStyleChangeListener());
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(new FontStyleChangeListener());
JPanel controlPanel = new JPanel();
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeComboBox);
controlPanel.add(new JLabel("Font:"));
controlPanel.add(fontComboBox);
controlPanel.add(boldCheckBox);
controlPanel.add(italicCheckBox);
add(textPane, BorderLayout.CENTER);
add(controlPanel, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class FontSizeChangeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int fontSize = Integer.parseInt((String) fontSizeComboBox.getSelectedItem());
textPane.setFont(new Font(textPane.getFont().getName(), textPane.getFont().getStyle(),
fontSize));
}
}
private class FontChangeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String fontName = (String) fontComboBox.getSelectedItem();
textPane.setFont(new Font(fontName, textPane.getFont().getStyle(), textPane.getFont().
getSize()));
}
}
private class FontStyleChangeListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int fontStyle = textPane.getFont().getStyle();
if (boldCheckBox.isSelected())
{
fontStyle |= Font.BOLD;
}
else
{
fontStyle &= ~Font.BOLD;
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC;
}
else
{
fontStyle &= ~Font.ITALIC;
}
textPane.setFont(new Font(textPane.getFont().getName(), fontStyle,textPane. getFont().
getSize()));
}
}
public static void main(String[] args)
{
new texteditor();
}
}
RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 13
MOUSE EVENTS
DATE:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class mouseevent extends JPanel
{
private String eventName = "";
public mouseevent()
{
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
eventName = "Mouse Clicked";
setBackground(Color.WHITE);
repaint();
}
public void mousePressed(MouseEvent e)
{
eventName = "Mouse Pressed";
setBackground(Color.PINK);
repaint();
}
public void mouseReleased(MouseEvent e)
{
eventName = "Mouse Released";
setBackground(Color.GREEN);
repaint();
}
public void mouseEntered(MouseEvent e)
{
eventName = "Mouse Entered";
setBackground(Color.MAGENTA);
repaint();
}
public void mouseExited(MouseEvent e)
{
eventName = "Mouse Exited";
setBackground(Color.BLUE);
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
eventName = "Mouse Dragged";
setBackground(Color.CYAN);
repaint();
}
public void mouseMoved(MouseEvent e)
{
eventName = "Mouse Moved";
setBackground(Color.RED);
repaint();
}
});
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (!eventName.isEmpty())
{
g.setFont(new Font("TimesNewRoman", Font.BOLD, 30));
int stringWidth = g.getFontMetrics().stringWidth(eventName);
int stringHeight = g.getFontMetrics().getHeight();
g.drawString(eventName, (getWidth() - stringWidth) / 2, (getHeight() - stringHeight) / 2);
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Mouse Event Listener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new mouseevent());
frame.setSize(400, 300);
frame.setVisible(true);
}
}
EX.NO: 14
ARITHMETIC CALCULATOR
DATE:

AIM:

To write a java program to create simple arithmetic calculator using grid layout and buttons

ALGORITHM:
Step 1: Start the program.
Step 2:
Step 3:
Step 4:
Step 5:
Step 6:
Step 7: Stop the program.

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class BuildCalculator extends JFrame implements ActionListener
{
JFrame actualWindow;
JPanel resultPanel, buttonPanel, infoPanel;
JTextField resultTxt;
JButton btn_digits[] = new JButton[10];
JButton btn_plus, btn_minus, btn_mul, btn_div, btn_equal, btn_dot, btn_clear;
char eventFrom;
JLabel expression, appTitle, siteTitle ;
double oparand_1 = 0, operand_2 = 0;
String operator = "=";
BuildCalculator()
{
Font txtFont = new Font("SansSerif", Font.BOLD, 20);
Font titleFont = new Font("SansSerif", Font.BOLD, 30);
Font expressionFont = new Font("SansSerif", Font.BOLD, 15);
actualWindow = new JFrame("Calculator");
resultPanel = new JPanel();
buttonPanel = new JPanel();
infoPanel = new JPanel();
actualWindow.setLayout(new GridLayout(3, 1));
buttonPanel.setLayout(new GridLayout(4, 4));
infoPanel.setLayout(new GridLayout(3, 1));
actualWindow.setResizable(false);
appTitle = new JLabel("My Calculator");
appTitle.setFont(titleFont);
expression = new JLabel("Expression shown here");
expression.setFont(expressionFont);
siteTitle = new JLabel(" II-B.Sc(CS) & II - BCA ");
siteTitle.setFont(expressionFont);
siteTitle.setHorizontalAlignment(SwingConstants.CENTER);
siteTitle.setForeground(Color.BLUE);
resultTxt = new JTextField(15);
resultTxt.setBorder(null);
resultTxt.setPreferredSize(new Dimension(15, 50));
resultTxt.setFont(txtFont);
resultTxt.setHorizontalAlignment(SwingConstants.RIGHT);
for(int i = 0; i < 10; i++)
{
btn_digits[i] = new JButton(""+i);
btn_digits[i].addActionListener(this);
}
btn_plus = new JButton("+");
btn_plus.addActionListener(this);
btn_minus = new JButton("-");
btn_minus.addActionListener(this);
btn_mul = new JButton("*");
btn_mul.addActionListener(this);
btn_div = new JButton("/");
btn_div.addActionListener(this);
btn_dot = new JButton(".");
btn_dot.addActionListener(this);
btn_equal = new JButton("=");
btn_equal.addActionListener(this);
btn_clear = new JButton("Clear");
btn_clear.addActionListener(this);
resultPanel.add(appTitle);
resultPanel.add(resultTxt);
resultPanel.add(expression);
for(int i = 0; i < 10; i++) {
buttonPanel.add(btn_digits[i]);
}
buttonPanel.add(btn_plus);
buttonPanel.add(btn_minus);
buttonPanel.add(btn_mul);
buttonPanel.add(btn_div);
buttonPanel.add(btn_dot);
buttonPanel.add(btn_equal);
infoPanel.add(btn_clear);
infoPanel.add(siteTitle);
actualWindow.add(resultPanel);
actualWindow.add(buttonPanel);
actualWindow.add(infoPanel);
actualWindow.setSize(300, 500);
actualWindow.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
eventFrom = e.getActionCommand().charAt(0);
String buildNumber;
if(Character.isDigit(eventFrom))
{
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(e.getActionCommand() == ".")
{
buildNumber = resultTxt.getText() + eventFrom;
resultTxt.setText(buildNumber);
}
else if(eventFrom != '=')
{
oparand_1 = Double.parseDouble(resultTxt.getText());
operator = e.getActionCommand();
expression.setText(oparand_1 + " " + operator);
resultTxt.setText("");
}
else if(e.getActionCommand() == "Clear")
{
resultTxt.setText("");
}
else
{
operand_2 = Double.parseDouble(resultTxt.getText());
expression.setText(expression.getText() + " " + operand_2);
switch(operator)
{
case "+":
resultTxt.setText(""+(oparand_1 + operand_2));
break;
case "-":
resultTxt.setText(""+(oparand_1 - operand_2));
break;
case "*":
resultTxt.setText(""+(oparand_1 * operand_2));
break;
case "/":
try
{
if(operand_2 == 0)
throw new ArithmeticException();
resultTxt.setText(""+(oparand_1 / operand_2));
break;
}
catch(ArithmeticException ae)
{
JOptionPane.showMessageDialog(actualWindow, "Divisor can not be ZERO");
}
}
}
}
}
public class Calculator
{
public static void main(String[] args)
{
new BuildCalculator();
}
}

OUTPUT:
RESULT:

Thus, the above program has been executed and verified successfully.
EX.NO: 15
TRAFFIC LIGHT
DATE:

AIM:

To write a java program to simulates a traffic light using radio buttons and text

ALGORITHM:
Step 1: Start the program.
Step 2:
Step 3:
Step 4:
Step 5:
Step 6:
Step 7: Stop the program.

PROGRAM:
import java.awt.Color;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
class app extends JFrame implements ItemListener
{
JFrame actualWindow;
JPanel messageContainer, lightsContainer;
JLabel message;
ButtonGroup btn_group;
JRadioButton rb_red, rb_yellow, rb_green;
app()
{
Font myFont = new Font("Verdana",Font.BOLD, 30);
actualWindow = new JFrame("Traffic Lights");
messageContainer = new JPanel();
lightsContainer = new JPanel();
message = new JLabel("SELECT LIGHT");
btn_group = new ButtonGroup();
rb_red = new JRadioButton("Red");
rb_yellow = new JRadioButton("Yellow");
rb_green = new JRadioButton("Green");
actualWindow.setLayout(new GridLayout(2, 1));
message.setFont(myFont);
rb_red.setForeground(Color.RED);
rb_yellow.setForeground(Color.YELLOW);
rb_green.setForeground(Color.GREEN);
btn_group.add(rb_red);
btn_group.add(rb_yellow);
btn_group.add(rb_green);
rb_red.addItemListener(this);
rb_yellow.addItemListener(this);
rb_green.addItemListener(this);
messageContainer.add(message);
lightsContainer.add(rb_red);
lightsContainer.add(rb_yellow);
lightsContainer.add(rb_green);
actualWindow.add(messageContainer);
actualWindow.add(lightsContainer);
actualWindow.setSize(500, 500);
actualWindow.setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
JRadioButton selected = (JRadioButton) ie.getSource();
String textOnButton = selected.getText();
if(textOnButton.equals("Red"))
{
message.setForeground(Color.RED);
message.setText("STOP");
}
else if(textOnButton.equals("Yellow"))
{
message.setForeground(Color.YELLOW);
message.setText("READY");
}
else
{
message.setForeground(Color.GREEN);
message.setText("GO");
}
}
}
public class trafficsignal
{
public static void main(String[] args)
{
new app();
}
}

OUTPUT:
RESULT:

Thus, the above program has been executed and verified successfully.

You might also like