PROGRAM 1:
// Finding Prime Numbers Less Than a Given Number
import [Link];
class PrimeNumbers
{
public static void main(String[]args)
{
int n;
int p;
Scanner s=new Scanner([Link]);
[Link]("Enter a number:");
n=[Link]();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
[Link](i);
}
}
}
OUTPUT:
PROGRAM 2:
//Matrix Multiplication
import [Link];
public class MatrixMultiplication
{
public static void main(String args[])
{
int n;
Scanner input=new Scanner([Link]);
[Link]("enter the base of squared matrices");
n=[Link]();
int[][]a=new int[n][n];
int[][]b=new int[n][n];
int[][]c=new int[n][n];
[Link]("enter the elements of 1st matrix row-wise\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=[Link]();
}
}
[Link]("enter the elements of 2nd matrix row-wise\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
b[i][j]=[Link]();
}
}
[Link]("multiplying the matrices...");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][j]*b[k][j];
}
}
}
[Link]("the product is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
[Link](c[i][j]+" ");
}
[Link]();
}
[Link]();
}
}
OUTPUT:
PROGRAM 3:
// Character, Line, and Word Counter
import [Link];
public class Statistics
{
public static void main(String[]args)
{
Scanner s=new Scanner([Link]);
int characterCount=0;
int lineCount=0;
int wordCount=0;
[Link]("enter text(type'exit'to finish):");
while(true)
{
String line=[Link]();
if([Link]("exit"))
{
break;
}
characterCount+=[Link]();
wordCount +=[Link]("\\s+").length;
lineCount++;
}
[Link]("Number of characters:" + characterCount);
[Link]("Number of lines:" + lineCount);
[Link]("Number of words:" + wordCount);
[Link]();
}
}
OUTPUT:
PROGRAM 4:
// Generate random numbers
import [Link];
import [Link];
public class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
Random y=new Random();
[Link]("enter maximum value:");
int max=[Link]();
[Link]("enter minimum value:");
int min=[Link]();
[Link]("Generating random number between"+min+"to"+max);
[Link]([Link](max-min+1)+min);
[Link]([Link](max-min+1)+min);
[Link]([Link](max-min+1)+min);
}
}
OUTPUT:
PROGRAM 5:
//StringManipulation
import [Link];
class Array {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();
char[] arr1 = [Link]();
char[] arr2 = [Link]();
// Fixed: use str1 instead of undefined variable 'str'
[Link]("1st string: " + str1);
[Link]("Enter index to find character (0-based):");
int pos = [Link]();
int length = [Link];
[Link]("Length: " + length);
if (pos >= 0 && pos < [Link]) {
// Fixed: use arr1[pos] instead of [Link](pos)
[Link]("Character at location " + pos + ": " + arr1[pos]);
} else {
[Link]("Invalid position");
}
// Concatenate two char arrays
char[] concat = new char[[Link] + [Link]];
int i = 0;
for (char c : arr1) {
concat[i++] = c;
}
for (char c : arr2) {
concat[i++] = c;
}
String result = new String(concat);
[Link]("Concatenating two strings: " + result);
[Link]();
}
}
OUTPUT:
PROGRAM 6:
//String Operations using string class
import [Link];
public class StringOp {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// 1. String Concatenation
[Link]("Enter first string: ");
String first = [Link]();
[Link]("Enter second string: ");
String second = [Link]();
String concatenated = first + " " + second;
[Link]("Concatenated string: " + concatenated);
// 2. Search Substring
[Link]("\nEnter a sentence: ");
String sentence = [Link]();
[Link]("Enter word to search: ");
String searchWord = [Link]();
if ([Link](searchWord)) {
[Link]("Substring '" + searchWord + "' found in sentence.");
} else {
[Link]("Substring '" + searchWord + "' not found.");
}
// 3. Extract Substring
[Link]("\nEnter a string to extract from: ");
String text = [Link]();
[Link]("Enter starting index: ");
int start = [Link]();
[Link]("Enter ending index: ");
int end = [Link]();
String extracted = [Link](start, end); // end index is exclusive
[Link]("Extracted substring: " + extracted);
[Link]();
}
}
OUTPUT:
PROGRAM 7:
// String operations using StringBuffer class
import [Link];
class Text {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input string
[Link]("Enter a string: ");
StringBuffer str = new StringBuffer([Link]());
// Reverse string
[Link]("Reversed string: " + [Link]());
// Calculate length of reversed string
[Link]("Length of reversed string: " + [Link]());
// Input new string for deletion
[Link]("Enter a new string for deletion: ");
str = new StringBuffer([Link]());
// Show length of new string
[Link]("Length of new string: " + [Link]());
// Deletion process
[Link]("Enter start index to delete substring: ");
int start = [Link]();
[Link]("Enter end index to delete substring: ");
int end = [Link]();
if (start >= 0 && end <= [Link]() && start < end) {
[Link](start, end);
[Link]("String after deletion: " + str);
[Link]("Length after deletion: " + [Link]());
} else {
[Link]("Invalid indices for deletion.");
}
[Link]();
}
}
OUTPUT:
PROGRAM 8:
// Multi-thread
import [Link];
import [Link];
class Thread1 extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("Thread1: " + i);
try {
[Link](100); // pause for 100ms
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
class Thread2 extends Thread {
public void run() {
for (int i = 90; i <= 100; i++) {
[Link]("Thread2: " + i);
try {
[Link](100); // pause for 100ms
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
public class Write {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
[Link](); // start thread1
[Link](); // start thread2
}
}
OUTPUT:
PROGRAM 9:
// Common Java Exceptions
public class Exc
{
public static void main(String[] args) {
// a. ArithmeticException
try {
int result = 10 / 0; // division by zero
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Caught ArithmeticException: " + e);
}
// b. NumberFormatException
try {
int num = [Link]("abc"); // invalid number string
[Link]("Number: " + num);
} catch (NumberFormatException e) {
[Link]("Caught NumberFormatException: " + e);
}
// c. ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught ArrayIndexOutOfBoundsException: " + e);
}
// d. NegativeArraySizeException
try {
int[] arr = new int[-5]; // negative size
} catch (NegativeArraySizeException e) {
[Link]("Caught NegativeArraySizeException: " + e);
}
}
}
OUTPUT:
PROGRAM 10:
// File Information Checker
[Link];
[Link];
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt the user for a file name
[Link]("Enter the file name (with path if not in the current directory): ");
String fileName = [Link]();
// Create a File object
File file = new File(fileName);
// Check if the file exists
if ([Link]()) {
[Link]("File exists: Yes");
// Check if the file is readable
[Link]("Readable: " + [Link]());
// Check if the file is writable
[Link]("Writable: " + [Link]());
// Display the type of file
[Link]("File type: " + ([Link]() ? "Directory" : "File"));
// Display the length of the file in bytes
[Link]("File length: " + [Link]() + " bytes");
} else {
[Link]("File exists: No");
}
// Close the scanner
[Link]();
}
}
OUTPUT:
PROGRAM 11:
// Frames and Controls
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class TextEditor extends JFrame {
private JTextArea textArea;
private JComboBox<String> fontComboBox;
private JComboBox<String> sizeComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
private JButton applyButton;
public TextEditor() {
// Set up the frame
setTitle("Text Editor with Font Controls");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create the text area
textArea = new JTextArea();
[Link](true);
[Link](true);
JScrollPane scrollPane = new JScrollPane(textArea);
// Create controls (Font, Size, Bold, Italic, Apply Button)
JPanel controlsPanel = new JPanel();
[Link](new FlowLayout());
// Font selection
String[] fonts = {"Arial", "Helvetica", "Times New Roman", "Courier"};
fontComboBox = new JComboBox<>(fonts);
[Link]("Arial");
// Font size selection
String[] sizes = {"8", "10", "12", "14", "16", "18", "20", "22", "24"};
sizeComboBox = new JComboBox<>(sizes);
[Link]("16");
// Bold checkbox
boldCheckBox = new JCheckBox("Bold");
// Italic checkbox
italicCheckBox = new JCheckBox("Italic");
// Apply button
applyButton = new JButton("Apply");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
applyFontSettings();
}
});
// Add components to the control panel
[Link](new JLabel("Font:"));
[Link](fontComboBox);
[Link](new JLabel("Size:"));
[Link](sizeComboBox);
[Link](boldCheckBox);
[Link](italicCheckBox);
[Link](applyButton);
// Add components to the frame
add(controlsPanel, [Link]);
add(scrollPane, [Link]);
}
// Method to apply selected font settings to the text area
private void applyFontSettings() {
String selectedFont = (String) [Link]();
int selectedSize = [Link]((String) [Link]());
int style = [Link];
if ([Link]() && [Link]()) {
style = [Link] | [Link];
} else if ([Link]()) {
style = [Link];
} else if ([Link]()) {
style = [Link];
}
// Set the font of the text area
Font newFont = new Font(selectedFont, style, selectedSize);
[Link](newFont);
}
// Main method to run the program
public static void main(String[] args) {
[Link](new Runnable() {
@Override
public void run() {
TextEditor editor = new TextEditor();
[Link](true);
}
});
}
}
OUTPUT:
PROGRAM 12:
// Mouse Events
import [Link].*;
import [Link].*;
public class MouseEventExample extends Frame {
// String to hold the name of the event
private String eventName = "";
public MouseEventExample() {
// Setting the window title and size
setTitle("Mouse Event Example");
setSize(400, 400);
setVisible(true);
// Adding MouseAdapter to handle all mouse events
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
eventName = "Mouse Pressed";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
eventName = "Mouse Released";
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
eventName = "Mouse Entered";
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
eventName = "Mouse Exited";
repaint();
}
});
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
eventName = "Mouse Dragged";
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
eventName = "Mouse Moved";
repaint();
}
});
// Closing the window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
// Overriding paint() method to display the event name at the center of the window
@Override
public void paint(Graphics g) {
[Link](g);
// Set the font and color for the event name text
[Link](new Font("Arial", [Link], 20));
[Link]([Link]);
// Draw the event name at the center of the window
FontMetrics metrics = [Link]();
int x = (getWidth() - [Link](eventName)) / 2;
int y = getHeight() / 2;
[Link](eventName, x, y);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
OUTPUT:
PROGRAM 13:
// Calculator
import [Link].*;
import [Link].*;
public class MyCalculator extends Frame implements ActionListener {
double num1,num2,result;
Label lbl1,lbl2,lbl3;
TextField tf1,tf2,tf3;
Button btn1,btn2,btn3,btn4;
char op;
MyCalculator() {
lbl1=new Label("Number 1: ");
[Link](50,100,100,30);
tf1=new TextField();
[Link](160,100,100,30);
lbl2=new Label("Number 2: ");
[Link](50,170,100,30);
tf2=new TextField();
[Link](160,170,100,30);
btn1=new Button("+");
[Link](50,250,40,40);
btn2=new Button("-");
[Link](120,250,40,40);
btn3=new Button("*");
[Link](190,250,40,40);
btn4=new Button("/");
[Link](260,250,40,40);
lbl3=new Label("Result : ");
[Link](50,320,100,30);
tf3=new TextField();
[Link](160,320,100,30);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
add(lbl1); add(lbl2); add(lbl3);
add(tf1); add(tf2); add(tf3);
add(btn1); add(btn2); add(btn3); add(btn4);
setSize(400,500);
setLayout(null);
setTitle("Calculator");
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
num1 = [Link]([Link]());
num2 = [Link]([Link]());
if([Link]() == btn1)
{
result = num1 + num2;
[Link]([Link](result));
}
if([Link]() == btn2)
{
result = num1 - num2;
[Link]([Link](result));
}
if([Link]() == btn3)
{
result = num1 * num2;
[Link]([Link](result));
}
if([Link]() == btn4)
{
result = num1 / num2;
[Link]([Link](result));
}
}
public static void main(String args[]) {
MyCalculator calc=new MyCalculator();
}
}
OUTPUT:
PROGRAM 14:
// Traffic Light
import [Link].*;
import [Link].*;
import [Link].*;
class extends JFrame implements ActionListener {
JLabel lbl1, lbl2;
JRadioButton rl,gl,ol;
ButtonGroup bg;
TrafficLights() {
Font fontL = new Font("Verdana", [Link], 70);
lbl1 = new JLabel();
[Link](170,30,300,200);
[Link](fontL);
add(lbl1);
Font fontR = new Font("Verdana", [Link], 16);
lbl2 = new JLabel("Select Lights");
[Link](20,250,130,50);
[Link](fontR);
add(lbl2);
rl = new JRadioButton("Red Light");
[Link](160,250,120,50);
[Link]([Link]);
[Link](fontR);
add(rl);
[Link](this);
ol = new JRadioButton("Orange Light");
[Link](300,250,150,50);
[Link]([Link]);
[Link](fontR);
add(ol);
[Link](this);
gl = new JRadioButton("Green Light");
[Link](460,250,140,50);
[Link]([Link]);
[Link](fontR);
add(gl);
[Link](this);
bg = new ButtonGroup();
[Link](rl);[Link](ol);[Link](gl);
setTitle("Traffic Light Simulator");
setSize(650,400);
setLayout(null);
setVisible(true);
}
// To read selected item
public void actionPerformed(ActionEvent ae) {
if([Link]() == rl)
{
[Link]("STOP");
[Link]([Link]);
}
if([Link]() == ol)
{
[Link]("READY");
[Link]([Link]);
}
if([Link]() == gl)
{
[Link]("GO");
[Link]([Link]);
}
}
// main method
public static void main(String[] args) {
new TrafficLights();
}
}
OUTPUT: